Zend Framework和Backbone.js

时间:2012-10-05 06:11:40

标签: php zend-framework backbone.js coffeescript

嗨,如果我想在我的zend应用程序中创建一个主干app / assets文件夹,我最有可能放置它? Backbone app文件夹由Javascript,Stylesheets and Templates

组成

简单地说,这就是骨干与rails配合使用的方式

routes.rb

  resources :entries  

Rails控制器用于条目/索引

class EntriesController < ApplicationController
    respond_to :json

    def index
        respond_with Entry.all
    end
end

如果网址位于/条目中

,则只需了解骨干网集合
class Blog.Collections.Entries extends Backbone.Collection
    url: '/entries'

在Backbone路由器

class Blog.Routers.Entries extends Backbone.Router
  routes:
    '': 'index'
    'entries/:id': 'show'

  initialize: ->
    @collection = new Blog.Collections.Entries()
    @collection.fetch()

  index: ->
    view = new Blog.Views.EntriesIndex(collection: @collection)
    #alert 'hi'
    $('#container').html(view.render().el)
  show: (id) ->
    alert "Entry #{id}"

然后呈现给Backbone.View

class Blog.Views.EntriesIndex extends Backbone.View

    template: JST['entries/index']

    initialize: ->
        @collection.on('reset',@render,this)
    render: ->

        $(@el).html(@template(entries: @collection))
        this

模板来渲染assets / templates / entries / index.jst.eco

<h1>Blog</h1>

<ul>
<% for entry in @entries.models: %>
    <li><%= entry.get('name')%></li>
<% end %>
</ul>

最后使用assets / javascripts / blog.js.coffee

初始化应用程序
window.Blog =
  Models: {}
  Collections: {}
  Routers: {}
  Views: {}
  initialize: -> 
    new Blog.Routers.Entries()
    Backbone.history.start()

$(document).ready ->
    Blog.initialize()

Backbone.js的上述MVC模式很有意思,但我想用Zend Framework实现,所以我必须改变配置才能使用我们在rails中使用它。同样我们如何处理模板来渲染视图?感谢

1 个答案:

答案 0 :(得分:0)

您可以将Backbone应用程序放在公共文件夹中(所有CSS和Javascript文件都在其中)。

对于模板,您可以使用首选的模板引擎,我使用Underscore来保存必须包含另一个库。这方面的一个例子是:

window.product_v = Backbone.View.extend({
    template: _.template("<article><img src='<%=icon%>'/> <% } %><article>"),

    render: function () {
        var self = this;
        this.model.fetch({
            processData: true,
            success: function (m) {
                var prod = $("<div/>", {
                        'html': self.template(m.toJSON())
                }).appendTo('.content');

            }
        });
    }
});

window.product_m = Backbone.Model.extend({
    urlRoot: '/api/get_product'
});

在你的模型中,你将在“urlRoot”中定义你的数据源,你可以在那里引用一个Zend控制器的路径。