调用视图中的骨干模型函数

Call backbone model function in view

本文关键字:模型 函数 视图 调用      更新时间:2023-09-26

我的模型中有一个简单的函数,如果优先级为100,则应该返回true

class App.Models.Publication extends Backbone.Model
  urlRoot: '/api/publications'
  isIncredible: ->
    @get('priority') is 100

在视图中我想调用这个函数,但是我不能

class App.Views.PublicationShow extends Backbone.View
  tagName: 'article'
  className: 'offer'
  template: JST['publications/show']
  render: =>
    if @model.isIncredible()
      $(@el).addClass('incredible').html(@template(publication: @model))
    else
      $(@el).html(@template(publication: @model))
    @modalEvent()
    this
我得到:TypeError: this.model.isIncredible is not a function

我用的是coffescript

您需要在视图中初始化模型,方法如下:1)在视图的初始化函数中设置模型

class App.Views.PublicationShow extends Backbone.View
  tagName: 'article'
  className: 'offer'
  template: JST['publications/show']
  initialize: ->
      @model = new App.Models.Publication()
  render: =>
    if @model.isIncredible()
      $(@el).addClass('incredible').html(@template(publication: @model))
    else
      $(@el).html(@template(publication: @model))
    @modalEvent()
    this

或2)在实例化模型实例时将模型实例作为参数传递给视图

pubModel = new App.Models.Publication(/*...*/)
pubShow = new App.Views.PublicationShow(model: pubModel)