2012-08-22 107 views
0
var ListView = Backbone.View.extend({ 
el: $('hello'), 
events: {       
     'click .myName': 'namefunc', 
}, 
initialize: function() { 
    var stuff = new FieldCollection(); 
    stuff.parse(); 
    var self = this; 
    stuff.fetch({ 
     success: function (collection, response) { 
      console.log(response); 
      self.render(response); 
      return response; 
     } 
    }); 
}, 
render:function(output){ 
    _.each(output, function(i){ 
     p=i.name; 
     $(this.el).append("<button class='myName'>"+p+"</button><h1>"+i.img+"</h1><br/>"); 
    },this);  

}, 
namefunc:function(){ 
    alert('hiii'); 
} 

如何綁定的變化與對誰按下按鈕的人的細節警報的HIII輸出...骨幹+結合

{ 
    "name": "john", 
    "img": "john.jpg", 
    "loc": "delhi", 
    "msg": "hello there" 
} 

這是即時得到的JSON .. ..when我點擊按鈕(有約翰的名字)應該顯示其味精....

+2

你能解釋一下這個問題比較好? – fguillen

+0

看看這個[post] [1]。所有你需要的 [1]:http://stackoverflow.com/questions/5270188/backbone-js-event-binding – schacki

+0

@fguillen現在檢查 –

回答

1
initialize: function() { 
var self = this; 
_.bindAll(this, 'render'); 
this.collection = new FieldCollection(); 
this.collection.parse(); 

this.collection.fetch({ 
    success: function (collection, response) { 
     console.log(response); 
     self.render(); 
    } 
}); 

},

render:function(){ 
var self = this; 
_.each(this.collection, function(model) { 
    // here you should create subviews and delegate events within particular view 
    // i.e: 
    // self.buttonViews.push(new ButtonView({ model: model})); 
    // but for now you can use data-id attribute to match the button you clicked 
    $(self.el).append("<button class='myName' data-id=" + model.id + ">" + model.name + "</button><h1>" + model.img + "</h1><br/>"); 
});  

},

namefunc:function(){ 
//use data-id attribute we put in button tag earlier to catch the id 
//and use this.collection.get('id') function to get the model you want to get parameters of 

}

1

,如果我理解你的問題,你可能只是做這樣的事情......

var _self = this, 
    obj = Object; 

$("<button>"+someVariable+"</button>") 
    .addClass('myName') 
    .appendTo(this.$el) 
    .on({ 
     "click": function() { _self.fn(obj) } 
    }); 

+0

另外,在骨幹你有一個jQuery對象this.el自動在此。$ el所以你不需要$(this.el) –

+0

沒有它沒有解決我的問題 –