Skip to content
This repository has been archived by the owner on Apr 18, 2023. It is now read-only.

Commit

Permalink
requirejs, node tests, mocha, readme improved
Browse files Browse the repository at this point in the history
  • Loading branch information
peremenov committed May 25, 2016
1 parent f3938bf commit 69ce161
Show file tree
Hide file tree
Showing 12 changed files with 248 additions and 150 deletions.
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
"env": {
"browser": true,
"commonjs": true,
"jquery": true
"jquery": true,
"amd": true
},
"extends": "eslint:recommended",
"rules": {
Expand Down
5 changes: 4 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,7 @@ node_js:
before_script:
- npm i

script: npm test
script:
- npm run lint
- npm run test
- npm run build
2 changes: 1 addition & 1 deletion Gulpfile.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
var gulp = require('gulp'),
qunit = require('gulp-qunit'),
qunit = require('gulp-mocha-phantomjs'),
uglify = require('gulp-uglify');

gulp.task('test', function() {
Expand Down
35 changes: 19 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,14 @@ Super simple, lightweight and solid factory of jQuery plugins. It allows to foll
## Features

- Support all modern browsers (including mobile browsers)
- Support Internet Explorer 6-8 (needs jQuery 1.8 or older)
- Support Internet Explorer 7-8 (needs jQuery 1.8 or older)
- Support jQuery version from 1.6
- Around 600 bytes compressed
- Efficient code re-usage when writing several plugins
- Support requirejs/webpack and amd
- Test mode

## Usage

### Install
## Install

Bower

Expand All @@ -35,24 +34,24 @@ Npm
npm install --save jquery-factory
```

### Plugin creation `$.newPlugin(pluginName, Constr, options)`
## Usage

**pluginName** — name of creating plugin. Should not contain name of existing plugins and internal jQuery methods
### Usage with requirejs or webpack

**Constr** — constructor Function for new plugin.

**options** — options object wich contain next props (could be Function for back compatibility with previous versions):
```javascript
var $ = require('jquery')(window),
newPlugin = require('jquery-factory')($);
```

* cb
* public
### Plugin creation `$.newPlugin(pluginName, Constr, options)`

Produces new jQuery plugin in `$.fn` object with **Constr** function. Factory accepts string **pluginName**. If plugin with the same name is exists factory throws an error.

`$.fn.pluginName` has `__constr__` property with **Constr** to check plugin accessory:
**pluginName** — name of creating plugin. Should not contain name of existing plugins and internal jQuery methods

```javascript
$('.element').data(pluginName) instanceof $.fn.pluginName.__constr__
```
**Constr** — constructor Function for new plugin.

**callback** — callback function (deprecated)

#### Constructor

Expand Down Expand Up @@ -82,6 +81,11 @@ Plugin instance stores with jQuery [`.data`](http://api.jquery.com/data/) method

You can enable test mode by giving **callback** argument to `$.newPlugin`. **callback** accepts plugin instance context and should return `true` to continue instance attaching or `false` to prevent it.

To check accessory of `$.fn.pluginName` use `__constr__` property with **Constr** to check plugin accessory:

```javascript
$('.element').data(pluginName) instanceof $.fn.pluginName.__constr__
```

### Examples

Expand Down Expand Up @@ -214,7 +218,6 @@ More examples available in [tests](https://github.com/peremenov/jquery-factory/b

You are welcomed to improve this small piece of software :)


## Author

- [Kir Peremenov](mailto:kirill@peremenov.ru)
Expand Down
16 changes: 12 additions & 4 deletions README.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,14 @@
## Возможности

- Поддержка всех современных браузеров (включая мобильные браузеры)
- Поддержка Internet Explorer 6-8 (необходима jQuery 1.8 или старше)
- Поддержка Internet Explorer 7-8 (необходима jQuery 1.8 или старше)
- Поддержка jQuery начиная с версии 1.6
- Около 600 байт в сжатом виде
- Эффективное реиспользование кода при написании нескольких плагинов
- Поддкржка requirejs/webpack и amd
- Режим тестирования

## Использование

### Установка
## Установка

Bower

Expand All @@ -35,6 +34,15 @@ Npm
npm install --save jquery-factory
```

## Использование

### Использование с requirejs или webpack

```javascript
var $ = require('jquery')(window),
newPlugin = require('jquery-factory')($);
```

### Создание плагина `$.newPlugin(pluginName, Constr, options)`

Создает новый jQuery плагин в `$.fn`-объекте с функцией-конструктором **Constr**. Фабрика принимает название плагина в виде строки **pluginName**. Если плагин с таким именем существует, будет брошена ошибка.
Expand Down
2 changes: 1 addition & 1 deletion dist/newPlugin.jquery.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

41 changes: 24 additions & 17 deletions newPlugin.jquery.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,47 @@
(function($, undefined) {
(function(root, factory) {
if ( typeof define === 'function' && define.amd ) {
define([ 'jquery' ], factory);
} else if ( typeof module == 'object' && module.exports ) {
module.exports = function($) {
return factory($);
};
} else {
if ( !root.jQuery )
throw new Error('jQuery must be defined');
root.jQuery.newPlugin = factory(root.jQuery);
}
})(this, function($, undefined) {
'use strict';

if ( !$ )
throw new Error('jQuery must be defined');

var noop = $.noop;
/**
* Default init options
* @type {Object}
*/
var defaultOptions = {
cb: function() { return true; },
// should be Array or null
public: null
ready: function() { return true; }
};

/**
* Creates plugin in $.fn object
* Creates new plugin in `$.fn` object. If plugin/method exists factory throws error.
* @param {String} __pluginName plugin name must be unique relative to other plugins and internal jQuery methods
* @param {Function} Obj plugin constructor Function
* @param {(Object|Function)} options plugin options or callback Function
* @return {Object} returns plugin object itself
*/
return $.newPlugin = function(__pluginName, Obj, options) {
var cb;
Obj = Obj instanceof Function ? Obj : function() {};
return function(__pluginName, Obj, options) {
var ready;
Obj = typeof Obj == 'function' ? Obj : noop;

/**
* Using for debugging, etc
* @return {Boolean} if true, stores new Object to data
*/
if ( options instanceof Function ) {
cb = options;
if ( typeof options == 'function' ) {
ready = options;
} else {
options = $.extend({}, defaultOptions, options);
cb = options.cb;
ready = options.ready;
}

/**
Expand Down Expand Up @@ -80,7 +87,7 @@
oldData;

if ( obj instanceof Obj ) {
if ( typeof opt == 'string' && obj[opt] instanceof Function )
if ( typeof opt == 'string' && typeof obj[opt] == 'function' )
obj[opt].apply(obj, params);
else
obj.update.apply(obj, args);
Expand All @@ -97,7 +104,7 @@

obj = new Obj($self, opt, oldData);

if ( cb.call(obj) )
if ( ready.call(obj) )
$self.data(__pluginName, obj);
}
}
Expand All @@ -107,4 +114,4 @@
fn.__constr__ = Obj;
return fn;
};
})( (typeof exports != 'undefined' && exports) || (typeof window != 'undefined' && window.jQuery) || {} );
});
14 changes: 9 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@
"test": "test"
},
"scripts": {
"test": "./node_modules/gulp/bin/gulp.js test",
"lint": "./node_modules/eslint/bin/eslint.js newPlugin.jquery.js"
"testbrowser": "./node_modules/gulp/bin/gulp.js test",
"testnode": "./node_modules/.bin/mocha ./test/tests-node.js",
"test": "npm run testnode && npm run testbrowser",
"lint": "./node_modules/eslint/bin/eslint.js newPlugin.jquery.js",
"build": "./node_modules/gulp/bin/gulp.js"
},
"repository": {
"type": "git",
Expand All @@ -31,11 +34,12 @@
"jquery": ">=1.6"
},
"devDependencies": {
"blanket": "1.2.3",
"chai": "^3.5.0",
"eslint": "2.10.2",
"gulp": "3.9.1",
"gulp-qunit": "1.4.0",
"gulp-mocha-phantomjs": "^0.11.0",
"gulp-uglify": "1.5.3",
"qunitjs": "1.21.0"
"jsdom": "^9.2.0",
"mocha": "^2.5.3"
}
}
40 changes: 40 additions & 0 deletions test/tests-data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
var pluginNameFactory = 'testfactory';
var pluginNameInstance = 'testinstance';
var pluginOptString = 'options';
var pluginOptObject = {
string: 'This is a test',
array : [ 1,2,'a']
};
var pluginOptArray = [1,2,'b'];
var pluginFunc = function($el, opt, old) {
this.$el = $el;
this.opt = opt;
this.old = old;

this.destroy = function() {
this.$el.removeData(pluginNameInstance);
};

this.update = function(opt, opt2, opt3) {
this.opt = opt;
this.opt2 = opt2;
this.opt3 = opt3;
}
};

var testEl = '#test';
var testWDataEl = '#test-w-data';
var testData = 'some useful data'; // the same as in HTML

if ( typeof module == 'object')
module.exports = {
pluginNameFactory: pluginNameFactory,
pluginNameInstance: pluginNameInstance,
pluginOptString: pluginOptString,
pluginOptObject: pluginOptObject,
pluginOptArray: pluginOptArray,
pluginFunc: pluginFunc,
testEl: testEl,
testWDataEl: testWDataEl,
testData: testData
};
16 changes: 16 additions & 0 deletions test/tests-node.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
var window = require('jsdom').jsdom('<div />').defaultView,
$ = require('jquery')(window),
factory = require('..')($);

var assert = require('chai').assert;

var data = require('./tests-data.js');

describe('require test', function () {

it('shoud has factory and create plugin', function() {
assert.equal('function', typeof factory(data.pluginNameFactory, data.pluginFunc));
assert.equal('function', typeof $.fn[data.pluginNameFactory]);
});

});
18 changes: 13 additions & 5 deletions test/tests.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,25 @@
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="../node_modules/qunitjs/qunit/qunit.js"></script>
<link href="../node_modules/qunitjs/qunit/qunit.css" rel="stylesheet">
<link rel="stylesheet" href="../node_modules/mocha/mocha.css" />
<script src="../node_modules/mocha/mocha.js"></script>
<script src="../node_modules/chai/chai.js"></script>
<script src="../node_modules/jquery/dist/jquery.min.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<div id="mocha"></div>

<div id="test"></div>
<div id="test-w-data" data-testfactory="some useful data"></div>
<div id="test-w-data" data-testinstance="some useful data"></div>
<script src="../newPlugin.jquery.js" data-cover></script>
<script>
mocha.setup('bdd');
mocha.globals(['jQuery']);
</script>
<script src="./tests-data.js"></script>
<script src="./tests.js"></script>
<script>
mocha.run();
</script>
</body>
</html>
Loading

0 comments on commit 69ce161

Please sign in to comment.