1

この質問に対する @20100 の回答に基づいて、バックボーン アプリケーションを再設計しています

コードのコメントを読んでください.


// My View
define([
    "js/collections/myCollection",
    "js/models/myFeed"
], function (MyCollection, MyModel) {
    var MyView = Backbone.View.extend({

        tagName: 'ul',

        initialize: function () {
            this.collection = new MyCollection();
            this.collection.on('add', this.onAddOne, this);
            this.collection.on('reset', this.onAddAll, this);

            // when I make myView = new MyView(_.extend( {el:this.$("#myView")} , this.options));
            // myView.render is not called
            // in order to trigger the render function I make the following… but probably there is a better way … 
            var that = this;
            this.collection.fetch({
                success: function () {
                    that.render();
                }
            });

        }
    });

    return MyView;
});

// MyCollection
define([
    "js/models/myModel"
], function (MyModel) {

    var MyCollection = Backbone.MyCollection.extend({
        model: MyModel, // add this
        url: function () {
            var url = "http://localhost/movies";

            return url; 
           // if I look to the GET request the url is without idAttribute
           // how can I attach the idAttribute to this url?
           // should bb takes care of this?

        }
    });

    return MyCollection;
});

//MyModel
define([
], function () {

    var MyModel = Backbone.MyModel.extend({
        idAttribute: 'object_id'
    });

    return MyModel
});
4

1 に答える 1

1

探求したい道は2つ

コレクションにモデル データを事前入力する

あなたの例では、すでにこれを行っていますが、コレクションを取得しています。コレクションの URL はhttp://localhost/moviesです。個々のモデルが必要な場合は、次のポイントを見てください。

必要なときにのみ個々のモデルをフェッチする

事前に入力されておらず、一度に 1 つのモデルをロードしているコレクションで ID を取得しようとしていると仮定すると、コレクションにメソッドをいくらか追加することによって、カスタムの方法でこれに少しアプローチする必要があります。これと同様に

getOrFetch: function(id, options) 
{
    var model;
    if (this.get(id)) 
    {
        model = this.get(id);
    } 
    else 
    {
      model = new this.model({
        id: id
      });
      this.add(model);
      model.fetch(options);
    }
    return model;
}

Backbone.Collection.prototype.getOrFetchまたは、必要に応じてすべてのバックボーン コレクションで使用できるように関数を追加します。

于 2012-05-17T11:16:36.287 に答える