Giter Site home page Giter Site logo

backbone.syphon's People

Contributors

adamwirth avatar azr avatar baig avatar blikblum avatar boriskozo avatar castus avatar courey avatar david-davidson avatar eliperelman avatar hanneskaeufler avatar hiroagustin avatar jamiebuilds avatar josemotanet avatar megawac avatar meomix avatar paulfalgout avatar rhubarbselleven avatar samccone avatar sapegin avatar scott-w avatar scttnlsn avatar sinewyk avatar sontek avatar starojitski avatar stephanebachelier avatar tpict avatar wesgibbs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

backbone.syphon's Issues

Disclude blank values from Syphon.serialize

Hi Derick!

I'm looking for where to start on changing the serialize behavior so that blank keys are not included in the object that Syphon returns. would changing the default key extractor be the right place to make this adjustment?

Right now I do this outside of Syphon, but I would like to implement it as an option for this library.

getVals: ->
  formData = Syphon.serialize @el
  # remove field names for blank values
  for field, val of formData
    delete formData[field] unless val
  formData

Uncaught TypeError: config.keyJoiner is not a function

I am getting the following errror:

Uncaught TypeError: config.keyJoiner is not a function

on this line of syphon code:

https://github.com/marionettejs/backbone.syphon/blob/v0.6.2/lib/backbone.syphon.js#L296

Here is my current front-end stack:

  "dependencies": {
    "backbone": "1.1.2",
    "backbone.paginator": "2.0.2",
    "backbone.picky": "0.2.0",
    "backbone.syphon": "0.6.2",
    "backgrid": "0.3.5",
    "backgrid-filter": "0.3.5",
    "backgrid-moment-cell": "0.3.5",
    "backgrid-paginator": "1730e0231c51d4606945a3d3492213ec37b9dcdc",
    "backgrid-select-all": "0.3.5",
    "bootstrap": "3.2.0",
    "bootstrap3-datetimepicker": "4.7.14",
    "highcharts-release": "4.0.3",
    "jquery": "1.10.2",
    "json2": "*",
    "marionette": "1.8.5",
    "moment": "2.5.1",
    "numeral": "1.5.3",
    "spin.js": "2.0.1",
    "underscore": "1.6.0",
    "moment-timezone": "0.2.2",
    "papaparse": "3.1.2",
    "async": "0.9.0"
  },
  "resolutions": {
    "underscore": "1.6.0",
    "moment": ">= 2.6.0"
  }

What might be wrong?

Using dot notation for nested attributes

Rather than the rails way of serializing nested values with [],
What is the best way to implement a serializer that allowed instead of:

foo[bar][baz] => foo.bar.baz

This would be easier to maintain in my case because the handlebar templates I'm writing out use dot notation to set the defaults, I have to write it out both ways currently and its painful to read and write, although working quite well.

Just curious. looks like I could override this function:
https://github.com/derickbailey/backbone.syphon/blob/master/src/backbone.syphon.keysplitter.js

input with no name errors

FYI, if you have inputs without names it causes an issue with Syphon
Uncaught TypeError: Cannot call method 'shift' of null

  // `["foo", "bar", ["baz"]] => {foo: {bar: {baz: ["value"]}}}`
  // 
  // When the final value is an array with a string, the key
  // becomes an array, and values are pushed in to the array,
  // allowing multiple fields with the same name to be 
  // assigned to the array.
  var assignKeyValue = function(obj, keychain, value) {
    var key = keychain.shift();

Syphon.deserialize issue with checkboxes

If you want to deserialize a model into multiple checkboxes it doesn't behave correctly.

For instance if you have a model like:

{languages: ['en']}

and a form:

<input name="languages[]" type="checkbox" value="en">
<input name="languages[]" type="checkbox" value="fr">

Then syphon will check both checkboxes.

Our current solution is to only check the checkboxes that actually match on the value like:

Backbone.Syphon.InputWriters.register("checkbox", function ($el, value) {
    if (_.isArray(value)) {
        if (_.contains(value, $el.val())) {
            $el.prop("checked", true)
        }
    } else {
       $el.prop("checked", value)
    }
})

Append semicolon to end of script

I use uglifyjs, which combines scripts together, and so its nice to have all my scripts ending with a semicolon so that they work well in it

bower update

Bower is still configured with Deriks version at derikbailey/backbone.syphon

Is this meant to be the maintained version?

Checkbox reader behavior is inconvenient for some possible uses.

I've been using Syphon while learning Marionette and I'm absolutely loving it. Recently I started using it for a production setup to collect a post's data before saving it and one of the model fields is an array of category IDs.

I have something like this for that particular field:

<input type="checkbox" id="category_1" value=1 name="categories[]"><label for="category_1">cat1</label>
<input type="checkbox" id="category_2" value=2 name="categories[]"><label for="category_2">cat2</label>
<input type="checkbox" id="category_3" value=3 name="categories[]"><label for="category_3">cat3</label>

I saw the documentation for changing the behavior for checkbox value collecting and so I modified the input reader for checkboxes like so:

Backbone.Syphon.InputReaders.register('checkbox', function(el) {
  if (el.is(":checked")) {
    return el.val();
  }
});

But I've found this is still adding an undefined value when a checkbox is not checked; for example if I select just the last two categories I get something like this

// the data contains this
[ undefined, 2, 3]

which I'm forced to clean after Backbone.Syphon.serialize(this) with a quick loop.

It would be cool to have a way to get only the actual values and not the undefined ones, as in if the value returned is null or undefined, don't add it to the data, unless there are implementation or other reasons behind not doing this.

Anyway, thanks a lot for your time and awesome libs.

Can't serialize into an array of objects

The rails form serializer allows creation of arrays of key/value pairs. For example,

<form>
   <div>
      <input type="text" name="people[][name]" value="John">
      <input type="text" name="people[][age]" value="35">
   </div>
   <div>
      <input type="text" name="people[][name]" value="Danny">
      <input type="text" name="people[][age]" value="28">
   </div>
</form>

would get serialized to

{people: [{name: "John", age: 35},{name: "Danny", age: 28}]}

As far as I can tell, Syphon just treats it like a single object, and overwrites all previous items in the array, and produces this:

{people: {name: "Danny", age: 28}}

Am I missing something, or is this just not doable with Syphon?

Adding File Input to Model

I have multipart/form-data Form with one File field. Below code is not getting the File data.

var data = Backbone.Syphon.serialize(this);

Is there any solution available n Syphone for File data ?

Ignoring empty field

Hey Derrick,

I was wondering if there's a configuration option or way to ignore empty fields? Can't find anything about it in the docs.

Thanks,

  • Steven

undefined keyExtractors

When I try to serialize a view, it gives the error:

Uncaught TypeError: Cannot call method 'get' of undefined 

on

var extractor = config.keyExtractors.get(type);

lib folder is not updated in major?

I really have two questions here:

  1. looking to major branch I see that src/backbone.syphon.js file was updated a year ago while the lib/backbone.syphon.js - 2. And so the second one doesn't have changes that was made in the first (e.g. I'm interested in disabled field ignore fix).

  2. correct me if I'm wrong but the npm build is still doesn't have major changes? E.g. same issue with ignore disabled seems to be merged to major year ago but never released?

Thanks!
Ilya

Provide more customizable formatter and writers

Syphon provides an ability to create custom input readers and writers for different data types. But type is always detected as tag name or type attribute. But sometimes I have to deal with custom data stored in the simple <input type="text">, but I still need to apply custom reader and writer for that fields.

Is there a way how to apply input readers and writers in the more customizable way? For example, add extra data-format attribute with additional information about field format.

.deserialize() infinite loop on circular refs.

Syphon.deserialize() doesn't like being fed data with circular references.

I was naively calling .deserialize(form, model.attributes) on a model that was part of a nested hierarchy where parent/children held references to each other as attributes (which is typical of projects using Backbone.Relational). This caused the flattenData() call to infinitely recurse.

Obviously I need to be more careful of what I pass to deserialize, but I scratched my head for a while before realizing the problem. Workaround is simple enough... just _.omit() the offending attributes.

Perhaps a warning note in the readme or source would be a good idea to help others? Currently there's no heads up re circular refs. I doubt implementing detection and handling is worth it, but might also be an alternative solution.

KeySplitter don't work for short parameter

Using parameter like 'q' failed into the keysplitter. It falsy consider it as an array.

Here is a proposal for fix :

Backbone.Syphon.KeySplitter = function(key){
  var matches = key.match(/[^\[\]]+/g);

  //Hack for short parameter
  if (key.length>2 && key.indexOf("[]") === key.length - 2){
    lastKey = matches.pop();
    matches.push([lastKey]);
  }

  return matches;
}

Add component.json for bower

Bower currently falls back to package.json and attempts to install the dependencies listed there. This is a known issue/"feature", but it would be nice to have this listed in the bower registry properly.

assignKeyValue should return obj if !keychain

Hi Derick,

If the field of the form doesn't have name, then function assignKeyValue checks for keychain and returns undefined while it should return obj.

  var assignKeyValue = function(obj, keychain, value) {
    if (!keychain){ return obj; }

Thanks for the great project.

Using :input instead of form

Currently, Syphon expects there to be a form element and from there will begin the serialisation process.

But what if there are 2 form tags? What if there isn't a form tag?

This issue is to land #18 (excluding handling default fields) by using :input as a means to collect form fields in a fragment

Resolve npm complaints

Following an npm install

npm WARN package.json Dependency 'backbone' exists in both dependencies and devDependencies, using 'backbone@^1.1.0' from dependencies
npm WARN package.json Dependency 'jquery' exists in both dependencies and devDependencies, using 'jquery@^1.8.0 || ^2.1.0' from dependencies
npm WARN package.json Dependency 'underscore' exists in both dependencies and devDependencies, using 'underscore@^1.6.0' from dependencies
npm WARN deprecated [email protected]: Please update to the latest version; it overrides noncompliant native methods even in modern implementations

Radio Buttons groups non selected default

Hi Derick,

First, I want to thank you very much your work on Backbone open source and your tons of tutorials online, they are extremely helpful for people getting into this world.

I've started using this plugin in the project I'm working right now and it's been great. But today I've found that when I serialize a form with a radio buttons group, without any radio selected, data serialized does not contain the key for that radio button group. I'm not sure if this is the intended behavior. This forces me to check for undefined.

Wouldn't it be better to have the name as a key of data and an empty string as its default?

Thanks, cheers
Miguel

Unselected radio group is not present in serialized data

Hi,

I've found that if you serialize a form with a radio group with no button checked, the serialize object will not contain any value. I would like to have a different behavior: provide the name (or whatever key is used) of the radio group with an empty value.

I can provide a PR if you are willing to accept this behavior.

Syphon deserialize not working on <select>

Deserialize is working fine for input and textarea but I can't get it working for the select tag.

Model Data

{
  id: 1
  items: [{name: "one"}, {name: "two"}, {name: "three"}]
}    

I've also tried with items: ["one", "two", "three"]

Command I execute

Backbone.Syphon.deserialize(view, model.toJSON())

Template

<select id="items" name="items" multiple="multiple"></select>

Compatibility issue with Cocktail Library

A function in Backbone.Syphon gets corrupted if (Backbone.Syphon - https://github.com/marionettejs/backbone.syphon) library is loaded before the (Cocktail - https://github.com/onsi/cocktail) library. I did not yet get to the bottom of it as to why but here is the problem.

Problem
If the Cocktail library is loaded after loading the Backbone.Syphon library then the Backbone.Syphon.keyJoiner, which is normally a function is now a string with value undefined[undefined]. It seems somehow the function was auto executed and the value was re-assigned on itself.

Expected

Backbone.Syphon.keyJoiner = function (parentKey, childKey){
  return parentKey + "[" + childKey + "]";
}

Actual

Backbone.Syphon.keyJoiner = 'undefined[undefined]'

Reproduce with the Breaking Situation

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://jashkenas.github.io/underscore/underscore-min.js"></script>
<script src="http://jashkenas.github.io/backbone/backbone-min.js"></script>
<script src="https://raw.githubusercontent.com/marionettejs/backbone.syphon/master/lib/backbone.syphon.js"></script>
<script src="https://raw.githubusercontent.com/onsi/cocktail/master/Cocktail.js"></script>
  <meta charset="utf-8">
  <title></title>
</head>
<body> 
  <script type="text/javascript">
    console.info('Backbone ' + Backbone);
    console.info('Syphon ' + Backbone.Syphon.keyJoiner); // undefined
  </script>
</body>
</html>

Reproduce with the non Breaking Situation

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://jashkenas.github.io/underscore/underscore-min.js"></script>
<script src="http://jashkenas.github.io/backbone/backbone-min.js"></script>
<script src="https://raw.githubusercontent.com/onsi/cocktail/master/Cocktail.js"></script>
<script src="https://raw.githubusercontent.com/marionettejs/backbone.syphon/master/lib/backbone.syphon.js"></script>
  <meta charset="utf-8">
  <title></title>
</head>
<body> 
  <script type="text/javascript">
    console.info('Backbone ' + Backbone);
    console.info('Syphon ' + Backbone.Syphon.keyJoiner); // function ...
  </script>
</body>
</html>

Linked Issue
onsi/cocktail#51

Add Backbone 1.3.* support

Because BB 1.2 breaks some webpack dependencies and this is only one package in my package.json which use BB 1.2. All other packages use 1.3.

Deserialize an undefined property matching a radio input

Hi, there is strong chance this issue is related to the #122, but because there is no way to be sure I created a new one, feel free to move it though.

It appears that if you deserialized an object with an undefined property, and if that property match a radio input you would get that error.

It all happens here l:420:

  // Radio button writer, set whether or not the radio button is
  // checked.  The button should only be checked if it's value
  // equals the given value.
  InputWriters.register('radio', function($el, value) {
    $el.prop('checked', $el.val() === value.toString());
  });

Because value would be undefined, value.toString would raised a "Cannot read property 'toString' of undefined".

Can submit the one line pr.

Trivial typo in line 68/69 of apidoc.md

The line reads:

  • To change the default behavior from using "id" to using "name" on input elements...

Where is should read:

  • To change the default behavior from using "name" to using "id" on input element

Backbone Syphon broken with Underscore 1.4+

Hello! I'm using Backbone Syphon in a project I'm currently developing. Yesterday I updated underscore to the last version (1.4.1) and now I'm getting an error when i call the serialize method:
"Uncaught TypeError: Cannot read property 'indexOf' of undefined"

I'm using the 0.4pre version cause I needed array serialization but the bug it's present in the stable 0.3 too. I don't know if Syphon it's currently discontinued since it has not been updated for a while, anyway I'm reporting the issue hoping for a fix :)

I put up a simple fiddle here: http://jsfiddle.net/HMnfs/3/

Thanks anyway and sorry for my bad english, I hope you will understand!

[NFR] set a class to syphon non-form elements

As contenteditable gets better and its use grows, there might be more demand for non-form extraction.

This could be a simple change.

return viewOrForm.$(':input');

to

return viewOrForm.$(':input, [contenteditable], .syphon-editablecontent');

Syphon.deserialze does not work with <select multiple> elements

I could definitely have something wrong on my end, but so far it seems like Syphon.serialize will take a multiselect and turn it into an array of strings, but pass the same array of strings back to Syphon.deserialize and the values do not get set. I see that the inputwriter delegates to $el.val(), so this should work OK.

On further investigation, It appears to be failing at Syphon.deserialize where the key is used to pull data:

Syphon.deserialize = function(view, data, options){
    /* ... */
    var value = flattenedData[key]; // <--------- This returns undefined, even though the console shows that this contains an array
    inputWriter($el, value);
  });

flattenedData at this point in the execution contains an array at the key of handedness, but it is not accessible for some reason.

flattenedData
  gender: "Female"
  guest: false
  handedness[]: Array[2]
  id: 37
  nickname: "[email protected]"
  state: null

Doesn't properly serialize checkboxes or radio buttons with DOM property set to checked=true

Using the attribute, like <input checked="checked"> works, but using a dom property does not. I used to think the attribute was the way to check a checkbox, until I read this answer: http://stackoverflow.com/a/18392577/111243

Now I see that there's a different thing called a DOM property. The new Bootstrap radio and check buttons (http://getbootstrap.com/javascript/#buttons-examples) use this method of marking the item checked, and backbone.syphon does not serialize it property, I think.

I'm looking more in to it and will update with more info.

Using with a Twitter Bootstrap styled form.

Maybe I've been misusing this, but In the lastest release version 0.5. I can style a form with bootstrap e.g. have nested divs with the inputs and when syphon is called it will pull out the nested inputs and serialize the data. With 0.6 it seems the change to the getForm function has removed this ability.

<form class="form-horizontal">           
        <div class="form-group">
            <label for="example" class="col-lg-2 control-label">Subject</label>
            <div class="col-lg-10">
                <input type="text" class="form-control" id="example" name="example">
            </div>
        </div>
</form>

Requiring $el to have `form` element

Very interesting and useful plugin! Thank you for this!

In my use case, I have a large <form>, in which I add/remove/replace smaller form HTML depending on the server's response to AJAX.

The smaller "forms" might be posted via AJAX themselves to the server, which requires me to serialize them using this plugin. Of course, they aren't <form> elements, as nested forms aren't allowed in HTML. So If I can change https://github.com/derickbailey/backbone.syphon/blob/master/src/backbone.syphon.js#L80 what issues might I face?

Was there a problem in not allowing extraction from any View?

When `viewOrForm.$el` is undefined, use `$.find`, not `$.children`?

Hi there,

I just ran into trouble with form serialization in a Marionette app. Turns out my problem involved Syphon's getForm function--specifically, the fact that it uses $.children, not $.find, to look for form inputs when passed a specific form, not a view.

My use case: I was passing a form to Syphon using Syphon.serialize(this.$('#my-form-id')[0]). (My view was a CompositeView whose $el included other forms [introduced by child views], so .serialize(this) would be too broad.) The form in question looked roughly like this:

<form id="my-form-id">
  <div class="row">
    <div class="form-group">
      <label for="name">Thing name</label>
      <input class="form-control" name="name"></input>
    </div>
  </div>
  <div class="row">
    <div class="form-group">
      <label for="info">Thing description</label>
      <textarea class="form-control" name="info"></textarea>
    </div>
  </div>
  <button type="submit" class="btn disabled">Save</button>
</form>

...that is, with multiple levels between the outer <form> tags and the inputs that I care about.

Within Syphon, in getForm, _.isUndefined(viewOrForm.$el) returned true, since the form itself doesn't have an $el. That meant getForm returned $(viewOrForm).children(':input'). But since $.children only looks one level deep, Syphon didn't find any matching elements and didn't extract any data.

So: since Backbone.View.$, which you use to handle views, uses $.find, and since $.find would find everything $.children does, why not go with $.find here, like this? master...david-davidson:use-jquery-find

Thanks for your time, and for your tremendously useful product!

Backbone Syphone serialization issue on selection of combobox items using tab

Hi All,

          I am using backbone.syphone to serialize my backbone forms.
          Its working fine in the normal case.
          I am using jqwidgets for Ui.
          So when i serialize the form containing jqxcombobox(item selected by tab not by mouse) its gives name in serialized data not value of selected item of combobox.

For Instance we have following content inn the form:
HTML:

Javascript:

        $("#contact_id").jqxComboBox({
            source: contacts,
            selectedIndex: -1,
            promptText: "Select Customer",
            width: '75.5%',
            height: '20',
            theme: 'ui-start'
        });

what is contacts:

                var contactItem = {
                    html: "",
                    label:A,
                    value:1
                };
                contacts.push(contactItem);
                var contactItem1 = {
                    html: "",
                    label:A,
                    value:1
                };
                contacts.push(contactItem1);

Now Serialization:

Case One : Select list item by mouse selection
It works well gives the value of selected index.
Case Two: Select list item by keyboard tab key.
It gives label string on serialization.

I need value of selected index in both cases.

Please suggest me a solution.

Thanks in advance.

Regards,
Pushpendra

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.