0

好的,我试图在 2 个单独的视图/集合中显示来自 json 文件的数据有点疯狂。

我将在这里粘贴我的整个代码并尝试解释我现在在哪里,以及我需要做什么。它可能是我只需要做的一件很小的事情才能让它工作,但我看不到它..

这是我的页面现在的屏幕截图,您可以看到正在加载数据,我只是无法将其正确放入视图中..

在此处输入图像描述

在我的 Collection 类中,我调用 parse:

parse:function(response, options) {
   return options.parseField ? response[options.parseField] : response;
},

我打电话给同步:(不确定它是否需要)

sync: function(method, model, options) {
options.contentType = "application/json";
options.cache = false;
options.dataType = "json";
return Backbone.sync(method, model, options);
},

然后在底部附近,我创建了 2 个新集合并使用 fetch 来获取每个集合所需的特定 json 数据,如下所示:

var links = new App.Collections.Links();
links.fetch({
  parseField: 'links_1',
  success: function () {
    console.log(links.toJSON());
            return links.toJSON();
  }
});

var links2 = new App.Collections.Links();
links2.fetch({
  parseField: 'links_2',
  success: function () {
    console.log(links2.toJSON());
            return links2.toJSON();
  }
}); 

我做了console.log,可以看到我的json数据加载得很好,但它没有被渲染?

我在这里做错了什么..

为了调试和理解,我在下面包含了我的整个 js 文件。

(function() {

// Helper functions

// Defining namespacing rules
window.App = {
    Models: {},
    Collections: {},
    Views: {}
};

// Setting global template function, for simpel declaration later on by setting template('name'); for the built in template function.
window.template = function(id) {
    return _.template( $('.' + id).html() );
};


// Capitalize first letter in a link by adding .capitalize(); to the string.
String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
};

// Extending Backbone 

//Modellen
App.Models.Link = Backbone.Model.extend({
    defaults: {
        navn : 'i haz a name!',
        link : 'http://www.lolcats.com/',
        counter : 0
    }
});


//Collection
App.Collections.Links = Backbone.Collection.extend({ 

    model: App.Models.Link,
    url: 'data1.json',

    parse:function(response, options) {
        return options.parseField ? response[options.parseField] : response;
    },

    sync: function(method, model, options) {
        options.contentType = "application/json";
        options.cache = false;
        options.dataType = "json";
        return Backbone.sync(method, model, options);
    },

    // Sort the models 'highest first'
    comparator: function(link) {
    return -link.get('counter');
    }       
});


//Singel view
App.Views.LinkView = Backbone.View.extend({
    tagnavn: 'li',

    template: template('Links'),

    initialize: function() {
        this.model.on('change', this.render, this);
        this.model.on('destroy', this.remove, this);
    },

    events: {
    'click .edit' : 'retLink',
    'click .delete' : 'destroy',
    'click .LinkUrl' : 'addCounter'
    },

    retLink: function() {
        var newLinkNavn = prompt('What should the new name be?', this.model.get('navn'));

        if ( !newLinkNavn ) return;

        newLinkNavn = newLinkNavn.capitalize();
        this.model.set('navn', newLinkNavn);


        var newLinkUrl = prompt('What should the new url be?', this.model.get('link'));
        if ( !newLinkUrl ) return;
        this.model.set('link', newLinkUrl);
    },      

    destroy: function() {
        this.model.destroy();

    },

    // Increment the counter then user clicks it
    addCounter: function(e) {
        e.preventDefault();
        var newCounter = this.model.get('counter');
        this.model.set('counter', newCounter + 1);
    },

    remove: function() {
        this.$el.remove();
    },

    render: function()  {
        this.$el.html(this.template(this.model.toJSON()) );
        return this;
    }
});

//Collection View
App.Views.LinksView = Backbone.View.extend({
    tagName: 'ul',
    className: 'liste',

    initialize: function() {
        _.bindAll(this);
        this.collection.on('add', this.addOne, this);
        this.collection.on('reset', this.render);

        // Render view when a user has changed a model          
        this.collection.bind('change', this.render, this); 

        $('.navnClass').focus();
        this.load();
        this.render();

    },

    load: function() {
        this.collection.fetch({
          add: true,
          success: this.loadCompleteHandler,
          error: this.errorHandler
        });     
    },

    loadCompleteHandler : function(){
        this.render();
    },

    errorHandler : function(){
        throw "Error loading JSON file";
    },

    render: function() {
        // Empty the UL before populating it with the new models and sorting it.
        this.$el.empty();
        this.collection.sort();

        this.collection.each(this.addOne, this);
        return this;
    },

    addOne: function(link) {
        var linkView = new App.Views.LinkView({ model: link });
        this.$el.append(linkView.render().el);
    }
});

// Create link view 
App.Views.AddLink = Backbone.View.extend({
    el: '#addLink',

    events: {
        'submit' : 'submit'
    },

    submit: function(e) {
        e.preventDefault();
        var linkNavn = $(e.currentTarget).find('.navnClass').val(),
             linkNum =  $(e.currentTarget).find('.linkClass').val();



        // Tildel link navn en værdi, hvis det er tomt   
        if ( ! $.trim(linkNavn)) {
                linkNavn = 'I haz a name!';
        }

        // Tildel link url en værdi, hvis det er tomt    
        if( ! $.trim(linkNum)) {
                linkNum = 'http://www.lolcats.com/';
        }

        // Tilføj http:// foran værdi, hvis den ikke indeholder det i forvejen.
        if( linkNum.indexOf( "http://" ) == -1 ) {
             addedValue = 'http://',
             linkNum = addedValue + linkNum;
        }

        // nulstil og sæt fokus på link navn feltet.
        $(e.currentTarget).find('.navnClass').val('').focus();
        $(e.currentTarget).find('.linkClass').val('');
        this.collection.add({ navn:linkNavn, link: linkNum });
    }

});


// new links collection
// populate collection from external JSON file
// change navn to match the link heading

var links = new App.Collections.Links();
links.fetch({
  parseField: 'links_1',
  success: function () {
    console.log(links.toJSON());
            return links.toJSON();
  }
});

var links2 = new App.Collections.Links();
links2.fetch({
  parseField: 'links_2',
  success: function () {
    console.log(links2.toJSON());
            return links2.toJSON();
  }
}); 


// new collection view (add)
var addLinkView = new App.Views.AddLink({ collection: links });

// new collection view
var linksView = new App.Views.LinksView({ collection: links });
$('.links').html(linksView.el);

// new collection view
var linksView2 = new App.Views.LinksView({ collection: links2 });
$('.links2').html(linksView2.el);   


})();
4

1 回答 1

0

你能试试这个:

var links2 = new App.Collections.Links();
links2.on("reset", function(collection){
   console.log("reset event", collection);
}
links2.fetch({
  parseField: 'links_2',
  wait:true, #wait for the server to respond
  success: function (collection, response) {
    console.log(collection, response);
  }
}); 

成功调用中的返回不执行任何操作(它将返回到 $.ajax 对象)。我添加了一个等待,因为如果它通过客户端验证,它会立即调用successcall(你没有,所以它总是首先调用success)。

你说它不会渲染任何东西。但是要渲染一些东西,你需要一个视图。我在您的代码中没有看到视图。

这是视图的一个简单示例:

var Link = new Backbone.View.extends({
    el: $('body'),
    initialize: function(){
       this.listenTo(this.collection, 'reset', this.render, this)
    },
    render: function(){
     this.$el.empty();
     this.collection.each(function(item){
        this.$el.append(item.get('id') + '<br />');
     });

    }
})
var view = new Link({collection: links2});
于 2013-02-15T09:40:33.480 回答