1

今天是我backbone.js在这里的第一天,所以请放轻松。我有 a view, acollection和 amodel填充 a select

我可以select硬编码 array的. 但我正在使用现有的 API,我需要先解析响应。这似乎也可以。

我不知道谁来告诉我发生了什么变化以呈现我新返回的结果/模型......如果这没有帮助,代码应该更有意义。

var UserGroup = Backbone.Model.extend();

var UserGroups = Backbone.Collection.extend({

    initialize:function(){
        this.fetch();
    },

    model: UserGroup,

    url: "http://myAPI/getUserGroups",

    parse: function(json){

        return json["GetUserGroups"]["Results"];
    }

});

var GroupSelectView = Backbone.View.extend({

    el: $("select"),

    initialize: function() {
        var that = this;

        this.collection = new UserGroups();

        this.render();

    },

    render: function(){
        _.each(this.collection.models, function(group){
            $("<option/>", { value: group.get("Id"), text: group.get("Name")} ).appendTo(this.el)
        }, this);
    },
});

var groupSelectView = new GroupSelectView();

你怎么看?我明白了吗?

4

3 回答 3

3

为了更加灵活,您可以收听resetadd事件。

集合是reset当您fetch从服务器(或本地)收集时,但如果您add建模或fetch使用add选项,则会触发每个模型的添加事件。

Backbone.js:获取

这应该有效:

var GroupSelectView = Backbone.View.extend({

    initialize: function() {
        var that = this;

        this.setElement($("select"));
        this.collection = new UserGroups();

        // listen to add and reset events but handle them differently
        // fired on collection.add(model) and collection.fetch({add: true})
        this.collection.on("add", this.renderItem, this);
        // fired on collection.fetch()
        this.collection.on("reset", this.render, this);

    },

    render: function(){
        // backbone collections already come with some underscore methods built in
        this.collection.each(this.renderItem, this);
    },

    renderItem: function(group) {
        this.$el.append($("<option/>", {
            value: group.get("Id"),
            text: group.get("Name")})
        );
    }
});
于 2012-10-09T13:06:05.023 回答
1

你可以做休耕...

var GroupSelectView = Backbone.View.extend({

    el: $("select"),

    initialize: function() {
        var that = this;

        this.collection = new UserGroups();
        this.collection.on( 'change', this.render, this );


    //  You could try this too, 1 is for 1 item is added, the other, when all items are changed
    //  this.postCollection.on('add', this.addOne, this);
    //  this.postCollection.on('reset', this.addAll, this);

        this.render();

    },

    render: function(){
        _.each(this.collection.models, function(group){
            $("<option/>", { value: group.get("Id"), text: group.get("Name")} ).appendTo(this.el)
        }, this);
    },
});
于 2012-10-09T12:54:58.303 回答
0

您可以使用Backbone.Events发布/订阅更改。点击链接了解更多信息。

模型和集合具有针对常见用例触发的内置事件,例如模型的属性发生更改(“更改”)和集合的模型已获取(“重置”)。

要触发更改(发布):

myObject.trigger('事件');

订阅更改(订阅者)

myObject.on('event',myCallback,context);

将 myCallback 设置为视图的渲染方法。

查看这篇文章,了解有关 Backbone 事件的更多详细信息。

于 2012-10-09T13:01:22.903 回答