当前位置:K88软件开发文章中心编程语言JavaScriptCoffeeScript → 文章内容

CoffeeScript 命令模式

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-15 15:34:13

由 珍珍阿姨 创建,Carrie 最后一次修改 2016-08-12 命令模式问题你需要让另一个对象处理你自己的可执行的代码。解决方案使用Command pattern传递函数的引用。# Using a private variable to simulate external scripts or modulesincrementers = (() -> privateVar = 0 singleIncrementer = () -> privateVar += 1 doubleIncrementer = () -> privateVar += 2 commands = single: singleIncrementer double: doubleIncrementer value: -> privateVar)()class RunsAll constructor: (@commands...) -> run: -> command() for command in @commandsrunner = new RunsAll(incrementers.single, incrementers.double, incrementers.single, incrementers.double)runner.run()incrementers.value() # => 6讨论以函数作为一级的对象且从Javascript函数的变量范围中继承,CoffeeScript使语言模式几乎看不出来。事实上,任何函数传递回调函数可以作为一个命令。jqXHR对象返回jQuery AJAX方法使用此模式。jqxhr = $.ajax url: "/"logMessages = ""jqxhr.success -> logMessages += "Success!\n"jqxhr.error -> logMessages += "Error!\n"jqxhr.complete -> logMessages += "Completed!\n"# On a valid AJAX request:# logMessages == "Success!\nCompleted!\n"

CoffeeScript 命令模式