Skip to content

Commit

Permalink
feat: add scope method
Browse files Browse the repository at this point in the history
  • Loading branch information
Fabien Motte committed Nov 15, 2017
1 parent ba4bb24 commit bc9d8fb
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/common/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ export { getURLFileExtension } from './getURLFileExtension'
export { isArray } from './isArray'
export { isCorsSupported } from './isCorsSupported'
export { isObject } from './isObject'
export { scope } from './scope'
export { uuid } from './uuid'
11 changes: 11 additions & 0 deletions src/common/scope.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* Bind methods on a given context
*
* @param {object} ctx Context
* @param {array} methodNames Method names
*/
export function scope (ctx, methodNames) {
for (let i = 0, l = methodNames.length; i < l; i++) {
ctx[methodNames[i]] = ctx[methodNames[i]].bind(ctx)
}
}
28 changes: 28 additions & 0 deletions test/common/scope.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { scope } from '../../src/common'

describe('common.scope()', () => {
it('Check if method is binded', () => {
const o = {
test () { return this }
}

const testCall = o.test()
scope(o, ['test'])

expect(testCall.hasOwnProperty('prototype')).toBeFalsy()
})

it('Check if methods are binded', () => {
const o = {
test1 () { return this },
test2 () { return this }
}

const test1Call = o.test1()
const test2Call = o.test2()
scope(o, ['test1', 'test2'])

expect(test1Call.hasOwnProperty('prototype')).toBeFalsy()
expect(test2Call.hasOwnProperty('prototype')).toBeFalsy()
})
})

0 comments on commit bc9d8fb

Please sign in to comment.