0

アプリケーションの主要な機能を再設計するときに、初めてバックボーンを使用します。目標は、同じバックボーンコレクション/ビューコードを使用して、同じページ上の複数の異なるリストを管理することです。機能はすべて同じで、変更されるのはデータだけです。

これまでのところ成功していますが、理解できない問題を発見しました。フォーム入力から新しいアイテムを追加すると、ビューはそれを処理し、コレクションのadd関数を呼び出してajaxで保存します。完了すると、コレクションは「additem」イベントを呼び出します。このイベントは、ビューの再レンダリングをトリガーすることになっています。

ただし、最後にロードされたビューのイベントのみが呼び出されます。イベント名を完全に変更して接頭辞を付け、ビューごとに一意にする必要がある場合でも、困惑します。

多くのコードが削除されていますが、問題のある部分は以下のとおりです。このコード例では、必要なリストタイプごとにイベントのプレフィックスを付けようとしましたが、間違ったビューでイベントを呼び出している場合は関係ありません。

// A collection is made to manage the data - saves to the server, loads, updates, etc
var ListItems = Backbone.Collection.extend({
    initialize: function(models, options) {
        this.url = options.url;
        this.options = options;
    },
    /**
     * We'll use a custom addItem handler so that we're not triggering
     * events or ajax requests on .add(), since .fetch() uses it
     */
    addItem: function(obj,ajax_elem){
        self_col = this;
        $.ajax({
            type: 'POST',
            url: this.options.add_url,
            data: obj,
            success: function(resp){
                if(resp.success === true){
                    console.log('collection calls ep ' + self_col.options.ep+':addItem');
                    Backbone.Collection.prototype.add.call(self_col, {text:obj.text,id:resp.id} );
                    self_col.trigger(self_col.options.ep+':addItem');
                } else {
                    self_col.trigger(self_col.options.ep+':error', resp.errors);
                }
                // ... rest of stuff



// View manages rendering the items to the page, etc
ListView = Backbone.View.extend({
    initialize: function(){
        self = this;
        this.ep = self.$el.attr('id');
        this.collection.bind(this.ep+":addItem",function(){
            console.log('view thinks ep is: ' + self.ep+":addItem");
            console.log(self.$el);
            self.render();
            $(window).trigger('Snowy:ajax:stop', self.$el.find(':submit'));
        });


// Load the category list
categoryList = new ListView({
    collection: new ListItems( INIT_CATEGORIES, {
        ep: 'categories',
        // other opts
    }),
    el: $("#categories")
});
4

1 に答える 1

1

問題は、グローバルを使用していることです。トリックを機能させるにはself = this、変数を現在のコンテキスト内で作成されたクロージャにキャプチャされるように、それらを割り当てる関数にローカル変数にする必要があります。

それ以外の

self = this;

行う

var self = this;

と同じself_col

于 2012-10-30T02:37:53.777 に答える