as-this
Call a javascript function with this
referred to the first argument
Primarily a syntactic sugar for CoffeeScript to replace long variable names with '@':
Install
npm install as-this
Usage
-
### as (self, fn)
call function, return the
self
object:as = require 'as-this'self =ret = as self->@msg = 'Hello, World'consolelog self # => { msg: 'Hello, World' }consolelog ret # => { msg: 'Hello, World' } -
### as.call (self, fn)
get the return value of
fn
instead ofself
:as = require 'as-this'ret = ascall msg: 'Hello, World' ->return @msgconsolelog ret # => 'Hello, World' -
### omits self
parameter
self
with be assigned to{}
if not specified:as = require 'as-this'ret = as ->@msg = 'Hello, World'consolelog ret # => { msg: 'Hello, World' } -
### defer with promise
return value with be wrapped as promise if
fn
returns a promise:as = require 'as-this'promise = as ->@msg = 'Hello, World'resolvepromisethenconsolelog ret # => { msg: 'Hello, World' }use co-yield to clean your non-blocking code (not available in browser environment):
co = require 'co'as = require 'as-this'co ->ret = yield as -> co =>@msg = 'Hello, World'consolelog ret # => { msg: 'Hello, World' } -
### yieldables
you may use generator function or thunk as
fn
value, they will be auto wrapped to promise:co = require 'co'as = require 'as-this'co ->ret0 = as ->@type = 'general'ret1 = yield as -> co =>@type = 'non-args function returns a promise'ret2 = yield as ->@type = 'generator function'yieldret3 = yield as@type = 'thunk'cbconsolelog ret0 # => { type: 'general' }consolelog ret1 # => { type: 'non-args function returns a promise' }consolelog ret2 # => { type: 'generator function' }consolelog ret3 # => { type: 'thunk' }
Scenario
-
### create object with interdependent properties
as = require 'as-this'urls = as ->@base = "http://host:port"@main = "/main"@list = "/list"@odd = "/odd"@even = "/even"...which is functionally equivalent to:
urls = do ->base = "http://host:port"list = "/list"returnbase: basemain: "/main"list: listodd: "/odd"even: "/even" -
### do complex configuration on a specified object
as = require 'as-this'ng = require 'angular'as ngmodule 'myApp'->@factory 'myServ' as ->=$httpget url=$httppost urldata@controller 'myController' as $scope->= ->myServload 'blahblah.json'then@data = res@doRefresh