这是我的简单Backbone应用程序,我边学习边学习。(用咖啡字体写的)
这个想法是,我有一个页面的x-y网格(1-1、2-1、1-2、2-2等)。页面加载并实例化带有这些ID的集合。当用户四处导航时(目前只向左和向右导航),整个模型从服务器加载,包括一些要显示的HTML。
它包含了一个模型、一个集合和一个视图,但我敢打赌我在错误的地方做事情!请告诉我出了什么问题。
Page = Backbone.Model.extend
displayHTML: (model, response) ->
$("#content").html(model.get('html'))
Pages = Backbone.Collection.extend
model: Page
url: "/pages"
current_page: '1-1'
initialize: (models, options) ->
this.fetch(success: this.displayFirst)
displayFirst: (collection, response) ->
model = collection.get(collection.current_page)
model.fetch(success: model.displayHTML)
nextPage: ->
id = "#{new Number(this.current_page[2]) + 1}-1" #todo - this will break with 9+
this.gotoPage(id)
previousPage: ->
id = "#{new Number(this.current_page[2]) - 1}-1" #todo - this will break with 9+
this.gotoPage(id)
gotoPage: (id) ->
this.current_page = id
if model = this.get(id)
model.fetch(success: model.displayHTML)
else
alert("Eh nooo")
AppView = Backbone.View.extend
el: $('body')
events:
"click #next-page": "nextPage"
"click #previous-page": "previousPage"
initialize: ->
this.pages = new Pages(null, {view:this})
nextPage: -> this.pages.nextPage()
previousPage: -> this.pages.previousPage()
appView = new AppView
如果它按您的意愿工作,那么它是正确的:)但您可以进行一些更改,以利用CoffeeScript+Backbone共同提供的某些功能。
第一个是声明一个类,你可以用这种方式写它以更简洁。
class Pages extends Backbone.Collection
将生成正确的JavaScript。
您可以做的另一个更改是用@
替换this.
的所有实例。你会从键入5个字符变成只键入1个字符。
以下是您发布的带有这些更改的内容的改写。希望我没有错过任何东西。
class Page extends Backbone.Model
displayHTML: (model, response) ->
$("#content").html(model.get('html'))
class Pages extends Backbone.Collection
model: Page
url: "/pages"
current_page: '1-1'
initialize: (models, options) ->
@fetch(success: @displayFirst)
displayFirst: (collection, response) ->
model = collection.get(collection.current_page)
model.fetch(success: model.displayHTML)
nextPage: ->
id = "#{new Number(@current_page[2]) + 1}-1" #todo - this will break with 9+
@gotoPage(id)
previousPage: ->
id = "#{new Number(@current_page[2]) - 1}-1" #todo - this will break with 9+
@gotoPage(id)
gotoPage: (id) ->
@current_page = id
if model = @get(id)
model.fetch(success: model.displayHTML)
else
alert("Eh nooo")
class AppView extends Backbone.View
el: $('body')
events:
"click #next-page": "nextPage"
"click #previous-page": "previousPage"
initialize: ->
@pages = new Pages(null, {view:@})
nextPage: -> @pages.nextPage()
previousPage: -> @pages.previousPage()
appView = new AppView
正如您所提到的,您可以使用视图来更改html。
并且不应该在initialize方法中调用new Pages()
。我更喜欢这种方式:类AppView扩展Backbone.View渲染:()->@collection#@collection是指您的页面集合
pagesCollection = new Pages()
appView = new AppView(
collection: pagesCollection
)
因为我认为模特和收藏品不应该知道这些景色。