Giter VIP home page Giter VIP logo

jcscript's Introduction

JCScript

This is a collection of JavaScripts to aid in the development of JS projects

Installation/Setup

Run:

npm install jcscript

Then, in your script:

import JCScript from 'jcscript';
var JCObject = JCScript.JCObject;

-- OR --

import { JCObject } from 'jcscript'

Examples

Use JCObject to create and access a simple object

/* Create new Employee model */
var Employee= new JCObject ({
    firstName: '',
    lastName: '',
    title: '',
    projects: {}
});
/* Populate with some data */
Employee.update({
    firstName: Joshua,
    lastName: Carter,
    title: Jr. Web Developer
});


/* Later in your code */
var name = Employee.get(['firstName', 'lastName']).join(' ');
Employee.update('title', 'Core Application Developer');

You can also use ES6 classes

/* Create Employee class */
var Employee= class extends JCObject {
    constructor (data) {
        /* Create model */
        super({
            firstName: '',
            lastName: '',
            title: '',
            projects: {}
        });
        //populate with data
        this.update(data);
    }
};
/* Create Employee */
var Joshua = new Employee({
    firstName: Joshua,
    lastName: Carter,
    title: Jr. Web Developer
});

Use JCFluxStore to do the same thing with a Flux model

/* Create new Employee model */
var Employee= new JCFluxStore({
    firstName: Joshua,
    lastName: Carter,
    title: Jr. Web Developer
}, {
    firstName: '',
    lastName: '',
    title: '',
    projects: {}
});


/* Later in your code */
Employee.addChangeListener(function () {
    $("#name").text(Employee.get(['firstName', 'lastName']).join(' '));
    $("#title").text(Employee.get('title'));
});

$("#promote").on('click', function (e) {
    Employee.Actions().update(Employee.get('id'), 'title', 'Core Application Developer');
});

Use ClientService to easily manage network requests

var Service = new ClientService ();
Service.get("http://www.example.com/api/employee/1").then(data => {
    Employee.update(data);
});
Service.ajax(
    "PUT",
    "http://www.example.com/api/employee/1",
    Employee.get(['firstName', 'lastName', 'title', 'projects'])
);

API

JCObject

A basic object class with getter and setter methods that can be inherited from when creating simple data stores.

constructor ([model])
  • model (obj) An object of property names and default values to use to create the object
get ([propSpec])

Gets a property value.

  • propSpec (str, array) The name(s) of the property(ies) to get (defaults to all properties)
  • returns (all) The property value, or an object of all properties requested
update (data[, val])

Updates with new data.

  • data (obj, string) A collection of properties and new values to update OR the name of a single property to update
  • val (string) If data is string (single prop), the value to update it to
  • returns (obj) This
reset ([propSpec])

Resets all properties to default values (or only specific properties if specified)

  • propSpec (str, array) The name(s) of the property(ies) to reset (defaults to all properties)
  • returns (obj) This

JCFluxStore

A basic Flux store modeled by a JCObject with built-in actions and dispatcher.

constructor ([data, model, Dispatch, Actions, AC])
  • data (obj) A collection of properties and values to populate the store with
  • model (obj) An object of property names and default values to use to create the store
  • Dispatch (Flux.Dispatcher) A Flux dispatcher to use instead of the built-in
  • Actions (obj) An object of Flux actions to make available instead of the built-in
  • AC (obj) An object of Flux action values to use instead of the built-in
get ([propSpec])

JCObject.get()

update (data[, val]) -- Triggers Change Event

JCObject.update()

reset ([propSpec]) -- Triggers Change Event

JCObject.reset()

addChangeListener (callback)
removeChangeListener (callback)

Add/remove a change listener that gets called when change events are triggered in the store.

  • callback (func) The listener to register
destroy ()

Disables store and removes registered listeners and actions

Built-In Actions

update (id, data[, val]) -> JCFluxStore.update()
  • id (int) The id of the object to update
  • Action parameters: data, val
  • Action name: UPDATE

JCFlux

A namespace object for holding the JCFlux api.

FluxStore

A basic Flux store meant to be extended by custom Flux store classes.

constructor ([Dispatch])
  • Dispatch (Flux.Dispatcher) A Flux dispatcher to register actions to (if not given, then no actions will be registerd)
addChangeListener (callback)
removeChangeListener (callback)

Add/remove a change listener that gets called when change events are triggered in the store.

  • callback (func) The listener to register
destroy ()

Disables store and removes registered listeners and actions

Properties
  • fluxActions (obj) Add actions to be called from the dispatcher
    • An action consists of a name key and method value
    • Example: fluxActions["AC-1"] = "update"; will call a method named update when an "AC-1" action is dispatched

ClientService

A service class for sending and handling network requests from clients with default functionality to automatically resend failed requests. This means that the service will wait for a successful HTTP status before resolving the returned promise while progressively waiting one second longer before each resend. The service can be configured to reject the returned promise instead of resending the request for specific HTTP statuses or all statuses. This configuration can be done globally or on a per request level. Authorization can also be handled by providing a value for the Authorization header and listening for invalid auth events. Requests are sent using jQuery.ajax(); settings properties to override those provided to jQuery.ajax() by default can be passed on a per request basis. Returned promises are from the Q library.

constructor ([auth, reject])
  • auth (string) The value of an Authorization header to send with the request
  • reject (int) An integer HTTP status code to reject a promise for by default
    • If a 4** or 5** code is received, the default behavior is to resend the request (waiting one second longer before each resend)
    • Any HTTP status codes passed will instead result in a rejection of the promise
  • reject (array[int]) An array of integer HTTP status codes
  • reject (string) The string 'all' will reject the promise for all failed requests
setAuth (auth)

Sets the auth value for the service (see ClientService.constructor()).

  • auth (string) The auth string to set
revokeAuth ()

Revokes the current auth value.

setReject (reject)

Sets the default reject value for requests (see ClientService.constructor()).

  • reject (string, int, array) The reject value to set
addInvalidAuthListener (callback)
removeInvalidAuthListener (callback)

Add/remove an invalid auth listener that gets called when the server invalidates the given auth string with a 401 HTTP status.

  • callback (func) The listener to register, function will receive the body of the response as an argument
ajax (method, url[, data, serviceOptions, ajaxOptions])

Send AJAX request to url.

  • method (string) The HTTP method to use (e.g. 'POST', 'DELETE', etc...)
  • url (string) The url to send the request to
  • data (obj) A JavaScript object to be sent to the API
    • (encoded as JSON if 'application/json' contentType -- default)
  • serviceOptions (obj) Service property values to use for just this request (overrides default values)
  • ajaxOptions (obj) Settings properties to pass to jQuery.ajax() for this request (overrides settings set by service)
  • returns (Q) A Q Promise
    • Resolved with (any) The body of the response parsed by jQuery.ajax()
    • Rejected with (array) The jqXHR object and the body of the response (parsed if JSON or XML)
    • Rejected with (string) If the call is cancelled while waiting to resend, the string "CANCELLED"
get (url[, params, serviceOptions, ajaxOptions])

Calls ClientSerivce.ajax() using GET method.

  • url (string) The url to send the request to.
  • params (obj) A JavaScript object to be sent to the API as urlencoded string
  • serviceOptions (obj) Service property values to use for just this request
  • ajaxOptions (obj) Settings properties to pass to jQuery.ajax() for this request
  • returns (Q) A Q Promise
getLastCallId ()

Gets the call id of the most recent request.

  • returns (string) The call id of the most recent request
cancel (callId)

Cancels a request with the given call id.

  • callId (string) The call id of the request to cancel

jcscript's People

Contributors

joshuacwebdeveloper avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

Forkers

stainlesscode

jcscript's Issues

Add `repeat` ClientService option to be counterpart to `reject`

Just like users can specify statuses that should be rejected (instead of repeating) on failed requests, they should also be able to specify statuses that should be repeated (instead of resolving) on successful requests.

Also, users should also be able to specify a callback for both options (callback determines whether request should be repeated/rejected).

Use configuration object to pass ClientService parameters to constructor

The ajax and get method calls accept the service parameters as a config object, but the constructor still accepts individual arguments.

Use the configuration class that will be created in #14.

Make this backwards compatible: detect when individual params are passed, but issue a deprecation warning when they are.

Allow resources to be removed/unset on destroyed store

If a method like removeChangeListener() is called on a destroyed store, then an error about a null resource is triggered. #20 will have errors/warnings thrown/logged when methods are called on destroyed stores; however, when methods like removeChangeListener() are called, they should not throw any errors at all. The reasoning: the user calls this method when they want to remove the listener, since the listener is already removed (because the store is destroyed) the method should act like it successfully removed the listener.

Consider not copying some types of objects in JCObject.get()

This behavior can cause problems when copying complex objects, such as a DOM element (but I think also for any non-plain object?). Consider only copying plain objects. Alternatively, better document the solution for having complex object values in JCObject, which is to define a separate getter for each of those properties.

Differentiate between no arguments and undefined argument in FluxStore.constructor()

FluxStore.constructor() takes an optional Dispatch argument. If the argument is not given, then a default dispatcher is used. However, if a value that equates to false is passed for the dispatcher argument, the default dispatcher will still be used; it would be better to throw an error.

Differentiate between a falsey value being passed as the Dispatch argument vs. no Dispatch argument being passed at all. If any Dispatch argument is passed, validate and throw an error if it isn't a valid Dispatcher.

Consider detecting and returning parse errors in ClientService rejected promises

Currently, if a request made through the ClientService results in a parse error, the resulting promise will be rejected with just the jqXHR object, and a value of undefined.

Consider instead, detecting the parse error (based on the errors given by jQuery), and assigning that error to the data value that is returned.

Allow Flux actions to be sent to multiple objects by specifying multiple ids

Currently, it is only possible to send an action to one object, or all objects that subscribe to the action type. This means that when the same action needs to be performed on a subset of the objects, that there is no clean way to do it (either have all objects receive the action and do additional checking, or have the action sent to the parent instead and have it calls its children).

Solution:
Accept a new ids prop on the action that will be an array of ids. Each FluxStore will check to see if it's id is in the array of ids.

Don't overwrite JCObject methods in JCFluxStore

Methods in JCObject call on other methods in the same class (i.e. reset calls update). When JCFluxStore overwrites update, then calling reset will inadvertently call JCFluxStore.update.

There shouldn't be a need to overwrite the methods in the first place, as they are action methods that shouldn't be directly called anyways. Exposing these methods at all is the tradeoff we have made to avoid having to wrap all the JCObject getters (as a component).

Rename the internal action methods JCFluxStore and don't overwrite the setters in JCObject. Keep the existing protected renamed methods for backwards compatibility, but emit a deprecation warning.

Problems with FluxStore.removeChangeListener()

  1. If the same function with different bindings (unequal functions) are added twice, the first is overwritten by the second and can't be removed.

  2. When a listener is removed, it isn't removed from the internal object maintained by FluxStore

Fix README.md

GitHub changed their support for some formatting in README.md, correct syntax.

Allow grouping of identical requests to be configurable in ClientService

Currently, if a user sends two identical requests to ClientService, it will only make one request and send the same result two both promises. There are situations where the user may want to actually make two identical requests, so this behavior should be made configurable.

The easy way would be to make it a Boolean, with default set to true. However, the original intent was to be a poor man's caching mechanism (application sends two identical GET requests, just burden the server with one request since it would be likely returning the same result); it may be better to have the default functionality be to group identical GET requests, but don't group identical requests that aren't GET (i.e. POST). This would require a more complex configuration mechanism.

Use custom Dispatch and ACTIONS in default JCActions service

JCFluxStore accepts a custom Dispatch, ActionsService, and ACTIONS constant. If any of them aren't passed then default values are used. However, the default JCActions service will always use the default dispatcher, even if a custom one is given to the store and used. This will result in the actions service dispatching actions to the wrong dispatcher. The same is true for the ACTIONS constant. This means that currently, the user is required to always either pass all three custom attributes if he wants any of them to be custom.

Don't add undefined listener in FluxStore.addChangeListener()

Currently, FluxStore.addChangeListener() will pass whatever value it is given to the addListener() method. It should check if it is given a function first.

If it isn't, it could either ignore it (do nothing) or throw/log an error. Decided which functionality is desired.

New Configuration class to model config properties for an application

  • Wrap around JCObject so that application could easily assign defaults, update, and get values.
  • Extend update() so that any object values would extend existing object values
  • Provide access and use validate.js to validate any config values (user would pass validation options to instance).
    • Attach custom validators for application to use

JCObject.get() should always return object when given an array

Currently, if JCObject.get() is given an array of exactly one property, then it will return the value of that property, as if it were given just that property name as a string. To be more consistent, JCObject.get() should instead return an object with just the one property in this instance.

The existing documentation around this behavior does not specifically say what is returned in this instance. I think technically, this won't have to be considered a backward-incompatible change. The documentation should be clarified on this point along with this change.

Allow full jqXHR object to be returned by promise via parameter

Allow a parameter/setting to be specified that would return the entire jqXHR object instead of just the data. The data should be saved as a property of the jqXHR object (maybe responseData or parsedData). It would be best to standardize this so that the jqXHR returned from a failure also matches. Maybe extend the jqXHR object in jQuery.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.