1

我正在尝试设置一个最简单的主干应用程序,该应用程序通过一组图像进行迭代。

我希望以下 url 影响下面的应用程序并放置 //??? 在问题所在的评论中:

网址:

http://localhost:3000/arc/location2/8   -> route to startapp
http://localhost:3000/arc/location2/8#image/1 -> route to image with collection.at(1)
http://localhost:3000/arc/location2/8#image/2 -> route to image with collection.at(2)

代码:

var imgsArray=[{'url':'/tmp-images/surf.jpg'},
    {'img':'/tmp-images/jamaica.jpg'},
    {'url':'/tmp-images/jamaica-2.jpg'}
];

arc.Image=Backbone.Model.extend({});
arc.Images=Backbone.Collection.extend({model:arc.Image});

var imgs=new arc.Images(imgsArray);
console.log(imgs.length);

var img=new arc.Image(imgsArray[0]);

查看代码和路由器:

arc.ItemView = Backbone.View.extend({
    el: $('#mig-container'),
    initialize:function(){
      this.model=this.collection.at(0);
      this.render(this.model);
    },
    render:function(){
       var html=this.model.get('url');
       this.$el.html(html);
       return this;
   }
});
var imgView=new arc.ItemView({collection:imgs});
var HexApp = Backbone.Router.extend({
    routes: {
        "": "startapp",
        "image/:index_id": "image"
    },
    startapp:function(){
        console.log("within startapp");
        imgView.render();
    },
    image:function(index_id){
        console.log("within image: " + index_id);
        // get Uncaught TypeError: Cannot call method 'at' of undefined in Chrome
        imgView.model=this.collection.at(index_id);  //??? no idea how to manipulate this
    }
});

hex={};

var app_router = new HexApp();
Backbone.history.start();

如何在 index_id 指定的索引处设置集合?还是有更惯用的方式来指定这一点?

提前谢谢

4

2 回答 2

2

路由器无法解析this.collection;这将引用collection您未定义的路由器实例中的属性。相反,您需要使用以下内容:

imgView.model = imgs.at(index_id);

imgs是您早期用于存储您定义的集合实例的变量。

于 2013-09-11T05:13:15.603 回答
0

如果我正确理解了您的问题,那么您的应用程序的初始状态会呈现集合中的第一张图像。当您点击image您希望imgView使用所选图像重新渲染的路线时,对吗?

只需查看代码,您几乎已经掌握了它。您需要做的最后一件事是在更新模型后重新渲染视图:

image:function(index_id){
    console.log("within image: " + index_id);
    imgView.model=this.collection.at(index_id);
    // re-render
    imgView.render();
}

否则,我认为该结构适用于示例应用程序。您需要修复第二项的声明,imgsArray所以关键是urlvs.img虽然。:)

于 2013-09-11T05:09:17.847 回答