获取骨干收集方法

时间:2013-07-31 19:46:12

标签: javascript backbone.js

我在集合上使用get backbone方法但是在同一个文件(路由器)中,在函数中工作而在其他函数中不起作用。将函数放在哪里不起作用

     var Models = {};
       var AppRouter = Backbone.Router.extend({

    routes: {
        "": "home",
        "user/:id":"userDetails",
        "settings":"settings",//mettere id dell utente loggato
        "friends":"friends",
        "mailbox":"mailbox",
        "landscape":"landscape",
        "gestione_richieste_amic":"gestione_richieste_amic"
    },

    friends: function(){
     console.log("friend_router");
     var self=this;
      Models.utenti = new Usercollection();
      Models.utenti.fetch({
      success: function(object) {
     console.log(object);


     var view=new FriendsView({model:object}); 
    self.changePage(view);

     },
     error: function(amici, error) {

    }
    }); 

    console.log(Models.utenti);
    var cur_user=Parse.User.current().id;

    console.log(Models.utenti.get(cur_user));<--undefined, don't works here
    console.log(cur_user); 






   }   ,

1 个答案:

答案 0 :(得分:1)

Ajax(获取方法)的异步特性的原因。

在获取集合之前,将执行您登录到控制台的行。所以你看到一个错误。

第一个选项 - 解决错误是将日志移到success处理程序内部

friends: function () {
         console.log("friend_router");
         var self = this,
             Models.utenti = new Usercollection();
         Models.utenti.fetch({
             success: function (object) {
                 console.log(object);
                 var view = new FriendsView({
                     model: object
                 });
                 self.changePage(view);
                 console.log(Models.utenti);
                 var cur_user = Parse.User.current().id;

                 console.log(Models.utenti.get(cur_user));
                console.log(cur_user); 
             },
             error: function (amici, error) {

             }
         });
     },

第二个选项 - 您可能会在集合上绑定sync事件。

initialize: function () {
     this.Models.utenti = new Usercollection();
     this.listenTo(this.Models.utenti, 'sync', this.logCollection);
     _.bindAll(this, 'logCollection');
 },
 logCollection: function () {
     console.log(this.Models.utenti);
     var cur_user = Parse.User.current().id;

     console.log(this.Models.utenti.get(cur_user)); 
    console.log(cur_user); 
 },
 friends: function () {
     console.log("friend_router");
     var self = this;
     this.Models.utenti.fetch({
         success: function (object) {
             console.log(object);
             var view = new FriendsView({
                 model: object
             });
             self.changePage(view);
         },
         error: function (amici, error) {

         }
     });
 },