CoffeScript类和绑定 [英] CoffeScript class and binding

查看:134
本文介绍了CoffeScript类和绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在CS类:

class Model
  constructor: (objectParams) ->
    @object = ##object
    ###constructor

  baseObject: => {}
  validate: ko.computed =>
    console.log ko.toJS @object

问题是与'验证'这是一个原型属性,其中ko.computed功能的结合方面应该是构造函数,而是被编译成这样的:

The problem is with 'validate' it is a prototype property where the binding context of the ko.computed function should be the constructor but instead gets compiled to this:

Model.prototype.validate = ko.computed(function() {
  return console.log(ko.toJS(Model.object));
});

我希望它被绑定到构造函数,但脂肪箭头=>似乎是工作仅是这样的:

I want it to be binded to the constructor but the fat arrow => seems to be working only this way:

property: () =>

和这样它不会工作。

  validate: =>
    ko.computed => console.log ko.toJS @object

由于ko.computed不能在函数内部定义

because ko.computed can't be defined inside a function

如何解决?

推荐答案

绑定你的函数的实例和preprocessing它的工作原理是这样

Binding your function to the instance and "preprocessing" it works like this

pipe = (fn)->
    return ->
        fn.apply(@, arguments)


class A
    foo: pipe -> @bar()
    bar: -> ...

从管道功能(在你的情况ko.computed)返回包装您最初的功能,并通过调用。适用用另一种功能。

from your pipe function (in your case ko.computed) return another function that wraps your initial function and calls it via .apply.

无需脂肪箭头你正在呼吁与@

No need for the fat arrow as your are calling apply with @

这篇关于CoffeScript类和绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆