douqudi5282 2014-01-09 11:13
浏览 48
已采纳

BackboneJS - 从PHP文件中获取数据并在View中显示

I'm fetching some data from my MySQL database with a php file and now I want to display this data in my View by passing it through a Model with the json_encode method. So far I created a Router, a Model, a Collection (is it necessary?) and a View. When i console.log the collection in my View, I can see that the data is actually there but my View shows nothing. When i console.log the Model I get the "undefined" message. So it seems that the Model is not instantiated, but I dont really know how to solve it. I use RequireJS and the HandlebarsJS for HTML templating purpose.

So here is my Router.

define(['backbone',
       'views/firstpage',
       'views/secondpage',
       'views/thirdpage',
       'collections/BandCollection']),
function( Backbone,FirstpageView, SecondpageView, ThirdpageView,BandCollection ) {
   var Router = Backbone.Router.extend({
        routes: {
            '': 'index',
            'firstpage' : 'firstpage',
            'secondpage' : 'secondpage',
            'thirdpage' : 'thirdpage'
          },
        initialize: function () {
           this.bandCollection = new BandCollection();

           this.bandCollection.fetch({
              error: function () {
              console.log("error!!"); 
            },
            success: function (collection) {
            console.log("no error"); 
          }
   });
},

        thirdpage: function() {
            var thirdpageView = new ThirdpageView({ el:'#topContent', collection:this.bandCollection}).render();

        },

    });

    return Router;
    }
 );         

My Model looks like this:

define([
"jquery",
"backbone"
],

function($, Backbone) {
var BandModel = Backbone.Model.extend({
    url: "../metal/db/bands.php",

    defaults: {
        "id": '',
        "band": '',
        "label": ''
    }
});

return BandModel;
});

My Collection:

define([
"backbone",
"models/BandModel"
],

function(Backbone, BandModel) {
var BandCollection = Backbone.Collection.extend({
    model: BandModel,
    url: "../metal/db/bands.php"
});

return BandCollection;
});

My HTML template:

<div>
   <p><%= id %></p>
   <p><%= band %></p>
   <p><%= label %></p>
</div>

And My View looks like this:

define(['backbone','handlebars', 'text!templates/Thirdpage.html'],

    function(Backbone,Handlebars, Template) {


        'use strict';

        var ThirdpageView = Backbone.View.extend({

            template: Handlebars.compile(Template),

            initialize: function () {
                _.bindAll(this, 'render');
                this.render();
            },

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

        });

        return ThirdpageView;

    }
);

As said before, the console.log(this.collection) tells me that the data is available..

{length: 6, models: Array[6], _byId: Object, constructor: function, model: function…} 

but console.log(this.model) gives me "undefined" - and the View actually displays the HTML mentioned before and not the data, meaning it actually shows

<div>
<p><%= id %></p>
<p><%= band %></p>
<p><%= label %></p>
</div>

So, can anyone help me out? I'm out of ideas...

  • 写回答

1条回答 默认 最新

  • donglipi4495 2014-01-09 11:42
    关注

    Change your render() method in your view like this:

    render: function() {
       var self = this;
       console.log(this.collection);
       self.collection.each(function(model){
            console.log(this.model);  // can view all models here
            self.$el.append(self.template({id:model.get('id'),band:model.get('band'),label:model.get('label')}));
       });
    
       return this;
    }
    

    Change your Template like this:

    <div>
      <p>{{id}}</p>
      <p>{{band}}</p>
      <p>{{label}}></p>
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码