2012-02-18 7 views
6

I am new to jQuery and I am using jQuery 1.7.1 to learn Knockout JS, I was following a video demo by the author. In his example he has a tag something like

<a href="#" class="button-delete">Delete</a> 

and in the viewmodel he has something like

$(document).on("click", ".button-delete", function() { console.log("inside"); }); 

When I tried in my side when I click on the delete button I never see the console.log show up on the console window of the Chrome F12 screen. I have two part question here

  1. Is there something I am doing wrong which is preventing the console message to show up?
  2. If I do not have a class to do css, is there any other way to perform the same task in the viewmodel?

edit: I corrected my typo, the code has proper parenthesis (I use web matrix so it take care of those issues). Here is my html

<!DOCTYPE html> 
<script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script> 
<script src="Scripts/knockout-2.0.0.js" type="text/javascript"></script> 
<script src="Scripts/ViewModel.js" type="text/javascript"></script> 
<html lang="en"> 
<head> 
    <meta charset="utf-8" /> 
    <title></title> 
    <link href="assets/css/bootstrap.min.css" rel="stylesheet"> 
</head> 
<body onload="init()"> 
    <input data-bind="value: tagsToAdd"/> 
    <button data-bind="click: addTag">Add</button> 
    <ul data-bind="foreach: tags"> 
      <li> 
       <span data-bind="text: Name"></span> 
       <div> 
        <a href="#" class="btn btn-danger" >Delete</a> 
       </div> 
      </li> 
    </ul> 
</body> 
</html> 

Here is my knockout viewmodel

/// <reference file="jquery-1.7.1.js" /> 
/// <reference file="knockout-2.0.0.js" /> 

var data = [ 
    {Id: 1, Name: "Ball Handling" }, 
    {Id: 2, Name: "Shooting" }, 
    {Id: 3, Name: "Rebounding" } 
]; 

function viewModel() 
{ 
    var self = this;  
    self.tags = ko.observableArray(data); 
    self.tagsToAdd = ko.observable(""); 

    self.addTag = function() { 
     self.tags.push({ Name: this.tagsToAdd() }); 
     self.tagsToAdd(""); 
    } 
} 


$(document).on("click", ".btn-danger", function() { 
    console.log("inside"); 
    }); 


var viewModelInstance; 
function init(){ 
    this.viewModelInstance = new viewModel(); 
    ko.applyBindings(viewModelInstance);  
} 

Respuesta

2

Parece que ya obtuvo su primera respuesta. En las "otras formas" de vincular el evento click si no tiene un nombre de clase, hay algunas opciones. Puede agregar una identificación a la etiqueta y llamarla de esa manera. O si no desea agregar una clase ni una identificación, puede usar la sintaxis de vinculación de datos con el enlace "clic" incorporado para invocar un método en su modelo de vista (obviamente este no es el estilo de jquery evnet, así que depende de usted cómo quiere conectar sus eventos). De esta manera:

<button data-bind="click: someMethod">Click me</button> 
18

Are you getting any errors?

Have you loaded the jQuery.js and the knockout.js

please post the code of view model.


ah! got it you have a typo

$(document).on("click", ".button-delete", function() { 
// console.log("inside"; <-- here it is 
    console.log("inside"); 
}); 

DEMO

+0

Consulte mis notas editadas. Tiene mi vista y mi modelo de vista. – Nair

+0

no soluciona el error tipográfico resuelto el problema? – JIA

+0

Cuando creé la pregunta, en lugar de copiar pegar el código, lo escribí, mientras lo escribía escribí el error tipográfico en la pregunta, pero el código tenía una paranthesis de apertura y cierre adecuada. – Nair

0

Nair primero que me haga saber que lo que se desea hacer aquí si quieres botón funciona eliminar. A continuación, utilizar la función de jQuery Ui eliminar y si quieres a la consola alguna cosa, entonces acaba de escribir console.log ("desea a la consola.");

Creo que su línea de function() { console.log("inside"; }); is wrong

0

yo recomendaría que se mira en el tecleo de unión por nocaut en vez de mezclar knockout con consulta aleatoria. El enlace de clic le permitirá vincular el evento click a una función en el modelo de vista.

+0

Acepto y puedo hacerlo funcionar en http://knockoutjs.com/documentation/foreach-binding.html pero estoy más interesado en saber por qué está fallando cuando uso el enlace mencionado en la pregunta. – Nair

Cuestiones relacionadas