2

我一直在用头撞墙好几个小时......看了很多页,我觉得我的脚本是正确的,但是我的收藏没有触发 add 事件 add: true 传入获取方法。我可以绑定到重置事件,但添加事件不会触发..

模型:

test.Models.AppBlock = Backbone.Model.extend({
    defaults: {
        AppID:          null,
        AppName:        null,
        AppDescription: null
    },
    idAttribute: "AppID"
});

收藏:

test.Collections.AppBlock = Backbone.Collection.extend({
    model:       test.Models.AppBlock,
    url:         ApiPath + "apps/byuser",

    Loading: false,

    initialize: function () {

    },

    getAppBlocks: function () {
        if (!this.Loading) {
            this.Loading = true;
            this.fetch({
                data: JSON.stringify({
                          Token: test.Session.Token
                      }),
                add:         true,  // OMG WTF ?!?!
                type:        'POST',
                dataType:    'json',
                contentType: 'application/json',
                cache:       false,
                success:     this.getAppBlocksSuccess,
                error:       this.getAppBlocksError
            });
        }
    },

    parse: function (response) {
        return response.Data;
    },

    getAppBlocksSuccess: function (that, response) {

    },

    getAppBlocksError: function (that, response) {

    }
});

看法:

test.Views.DashboardLatestMain = Backbone.View.extend({
    Loading: null,

    initialize: function () {
        this.template = _.template(test.Templates.DashboardLatestMain);
        this.collection.bind('add', this.addAppBlock);
        this.render();
    },

    render: function () {
        $('#latest').prepend(this.template);
        this.Loading = new test.Views.Loading({
            el: '.main'
        });
        this.collection.getAppBlocks();
    },

    addAppBlock: function (appBlockModel) {
        alert(appBlockModel); // no dice....
        var appBlockView = new test.Views.AppBlock({
            model: appBlockModel,
            el: '#latest .main h3',
            After: true
        });
    }
});

任何帮助是极大的赞赏。

编辑

api返回的数据:

{
    "Status":["1","OK"],
    "Data":[{"AppID":1,"AppName":"test","AppDescription":"test"},
            {"AppID":2,"AppName":"test","AppDescription":"test"}]
}
4

1 回答 1

9

在 Backbone 0.9.9 集合fetchreset,默认情况下会触发一个“重置”事件。在 1.0 中,fetch 执行一个update(现在称为set),并默认触发 'add'、'remove' 和 'change' 事件。

所以,要么更新到 1.0,你现有的代码应该可以工作。或者,添加update:true到您的fetch通话中(您不需要add:true,因为这是默认设置)。

于 2013-04-03T14:07:31.123 回答