BackboneJS和Codeigniter - 在同一视图中显示多个RESTful API

时间:2014-01-28 12:31:02

标签: php mysql json codeigniter backbone.js

好的,我试着尽可能地解释它。我有一个MySQL数据库,其中有一个名为artists的表,它存储来自a-z的艺术家/乐队。我正在使用PHP框架Codeigniter作为我的后端。现在我创建了一个JSON文件,我通过模型和集合在特定视图中进行渲染。我的JSON看起来像这样:

[
{
    "name":"0-9",
    "id":"0",
    "url":"0-9"
},
{
    "name":"A",
    "id":"1",
    "url":"A"
},
{
    "name":"B",
    "id":"2",
    "url":"B"
},
{
    "name":"C",
    "id":"3",
    "url":"C"
},
{
    "name":"D",
    "id":"4",
    "url":"D"
},
    ....etc etc.

然后我的HTML模板看起来像这样(使用Handlebars):

<ol class="alist">
    {{#each alphabetlist}}
    <li data-id="{{this.url}}">{{this.name}}</li>
    {{/each}}
</ol>

我的视图看起来像这样:

function(Backbone,Handlebars, Template) {


    'use strict';

    var AlphabetListView = Backbone.View.extend({

        template: Handlebars.compile(Template),

        events: {
            'click li':'li_clickHandler'
        },

        li_clickHandler: function(e) {
            var id = $(e.currentTarget).attr('data-id');
            Backbone.history.navigate('/artists/'+id, {trigger:true});
        },

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

    });

    return AlphabetListView;

}

所以,我想要做的是,使用Codeigniter的RESTful API插件为每个字母创建一个API。我为每个字母创建了一个API。例如,对于字母 C

,请执行此操作
  <?php

  require(APPPATH.'libraries/REST_Controller.php');

 class Cartists extends REST_Controller{

 public function index_get()  
 { 
  $this->load->database();
  $sql = 'SELECT id, name FROM artists WHERE name LIKE="C%"';
  $query = $this->db->query($sql);
  $data = $query->result();

  if($data) {
      $this->response($data, 200); // 200 being the HTTP response code
    } else {
     $this->response(array('error' => 'Couldn\'t find any artists with letter c!'), 404);
 }
}

然后,在我的Backbone模型中,我做了:

function($, Backbone) {
var CartistsModel = Backbone.Model.extend({
    url: "../ci/index.php/api/cartists/index",

    defaults: {
        "id": '',
        "name": ''
    }
});

return CartistsModel ;
});

我的收藏:

function(Backbone, CartistsModel ) {
var CartistsCollection = Backbone.Collection.extend({
    model: CartistsModel ,
    url: "../ci/index.php/api/cartists/index"
});

return CartistsCollection;
 });

现在我的目标是在点击相关信后获得正确的收藏。例如,点击字母C,它向我显示所有带有字母C的艺术家。当我点击字母M时,它向我显示所有M等艺术家。我觉得我很接近,但是现在我有点丢失或者真的不知道如何解决这个问题...

有什么建议吗?

0 个答案:

没有答案