【问题标题】:backbone + binding骨干+结合
【发布时间】:2012-08-22 09:41:54
【问题描述】:
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....当我点击按钮(有约翰的名字)时,它应该显示它的 msg....

【问题讨论】:

  • 你能更好地解释这个问题吗?
  • 查看此 [帖子][1]。所有你需要的[1]:stackoverflow.com/questions/5270188/backbone-js-event-binding
  • @shacki 那篇文章不是我要找的
  • 我认为您应该在这里解决的不仅仅是一件事。例如,您通过LisView 管理所有元素事件,而不是使用SubViews 作为元素。您将fetch() 响应直接发送到render(),而不是使用适当的骨干集合,......所以在这里很难得到一个简单的答案.. 尝试将这一切组织得更好。
  • 那么请更详细地解释问题是什么,您希望发生什么以及会发生什么。

标签: json backbone.js


【解决方案1】:

如果我理解了你的问题,你可以这样做......

var _self = this, 
    obj = Object;

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

【讨论】:

  • 另外,在主干中,您在 this.$el 中自动有一个 this.el 的 jquery 对象,因此您不需要 $(this.el)
【解决方案2】:
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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    相关资源
    最近更新 更多