Git Product home page Git Product logo

knockout.punches's Introduction

Knockout.Punches

Using the new APIs in Knockout 3.0.0, this plugin provides a set of enhanced binding syntaxes.

  1. Embedded text and attribute bindings
  2. Text filters
  3. Namespaced dynamic bindings
  4. Wrapped event callbacks
  5. Expression-based event handling

Download

Documentation

License and Contact

License: MIT (http://www.opensource.org/licenses/mit-license.php)

Michael Best
https://github.com/mbest
[email protected]

knockout.punches's People

Contributors

bestguy avatar brianmhunt avatar mbest avatar sloria 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

knockout.punches's Issues

Feature Request: Add parsing of html inside of {{ }} and {{{ }}} binding syntax

So I was able to import markdown into views and still use knockout punches inside of that markdown, but I have one issue.

I'm trying to pass in some html as a parameter to a i18next function inside of my markdown
- {{{ko.t('welcome:Markdown',{link:"[markdown](#markdown)"})}}}

This is the output
<li>{{{ko.t('welcome:Markdown',{link:"<a href="#markdown">markdown</a>"})}}}</li>

Any chance of getting the interpolation to traverse that gap? I've been quite surprised so far that everything has worked with the markdown, but this is the only issue I've encountered so far.

enableAll() does not call enableAttributeInterpolationMarkup()

From the docs (for 0.3.0) I get the impression that enableAll will give me all the features described on the page, but when running it I don't get the attribute interpolation feature unless I manually enable it. Is this intended (attribute interpolation isn't included when you enable all features)?

I temporarily fixed in my version by adding enableAttributeInterpolationMarkup() below https://github.com/mbest/knockout.punches/blob/master/src/utils.js#L71, but not that familiar with this code so not sure if that's proper.

Thanks

Dynamic binding problem when using html binding

Hi,

When I write {{something}} to textarea, knockout try to apply binding then it causing error.

{{something}} is not binding expression, it just a text from user input.

How can I prevent this dynamic binding?

<textarea data-bind="value:code"></textarea>

Preview:
<div data-bind="html:code">

</div>

Nuget update?

The nuget repository is stuck at 0.3.0. Neither 0.3.1 nor 0.4.0 are available there.
Could you update the feed please?

BTW thanks for your work on KO and punches, this library has become the cornerstone of all my web projects! It rocks ;)

Access current bindingContext in filters - is it possible to do this?

Background: we built a "trans" (translation) filter - that actually uses translation messages of a Symfony2 backend - and can be used e.g. like so:

{{ 'translate-this' | trans : 'translation-domain' }}

We want to be able to set the default translation domain like so
{{# transDefaultDomain: 'whatever' }}
{{ 'translate-this' | trans }}
{{ 'and-this' | trans }}
{{/ transDefaultDomain }}

so that for multiple translations the domain has not to be given per element ...

Therefore our trans-filter needs to access the current binding context ...

Best Regards

P.S.: We love your extension.

Pure Computed, is this supposed to work?

I have a pure computed defined as follows

`
self.minDate = ko.pureComputed({

    read: function () {

        return minimumDate;

    },
    write: function (v) {
        var p = new Date(v);
        console.log(p);
        if (p < minimumDate()) {
            minimumDate(p);
        }
    },
    owner: self
});

`

but when I do {{minDate}} it pastes the functions code, not the value, and if I do {{minDate()}} it executes it on load and gets the initial value, but then it doesn't update of course. So I'm guessing that pure computeds aren't supported yet? Or am I doing something wrong?

Also, I'm not sure a pure computed is the proper way to handle what I'm doing, so feel free to enlighten me if I'm just being dumb :) I am loading multiple datasets from ajax, and just trying to track the min date brought it without redrawing my UI for each record brought back unless the date actually changes. So when I get the result set back, I iterate it and pass in each date to my pure computed.

Not valid HTML markup?

It looks quite nice! I like the approach!
Although it seems that using this plugin the HTML markup won't validate anymore when using things such as:

<ul>
    {{#foreach: items}}
        <li>The current item is: {{name}}</li>
    {{/foreach}}
</ul>

I guess the approach to it is by combining it with knockout binds?

<ul>
    <!-- foreach: items -->
        <li>The current item is: {{name}}</li>
    <!-- /ko -->
</ul>

getting error "autoNamespacedPreprocess is not defined"

I think it is related to the following code in

// Set the namespaced preprocessor for a specific binding
function enableAutoNamespacedSyntax(bindingKeyOrHandler) {
    setBindingPreprocessor(bindingKeyOrHandler, autoNamespacedPreprocess);
}

i think autoNamespacedPreprocess should be autoNamespacedPreprocessor

Support for other bindings?

Will other bindings be supported in the future? Such as if, with and foreach?

{{ foreach: data }} ... {{ /foreach }}

Enable Everything by Default

Just curious - why the decision to make it so that all of the ko-punches syntaxes have to be explicitly enabled?

What would be the problem with simply turning all of the new features on by default and applying the new features for all by bindings? I want to upgrade my knockout, but I have so many bindings that enabling them all would be incredibly tedious.

support multiple css bindings per element

Knockout data-bind supports multiple css bindings. It would be helpful for punches to do the same.

data-bind example

<input type="text" data-bind="title: title
    , css: fields.inputsize.value
    , css: fields.color.value
    " />

desired in punches

<input type="text"
css="{{fields.inputsize.value}}"
css="{{fields.color.value}}"
/>

workaround in punches

<input type="text"
css="{{fields.inputsize.value         +       ' '    +    fields.color.value}}"
/>

self closing binding

Any chance of a self closing binding?

something like ...

{{#bindingname/}}

just to save me some valuable key strokes :P

Filter compatibility with knockout-secure-binding?

Was attempting to use ko.punches filter syntax with secure binding provider from https://github.com/brianmhunt/knockout-secure-binding.

Works fine with just text {{ example }}, but getting an error when using text filters such as {{ text | uppercase }}. Error is:

Expected ',' but got ':';

This provider gets around CSP limitations in Chrome apps, etc by avoiding eval. I think this issue is due to the filter syntax, which is not valid JSON:

<!--ko text: 'u' | repeat: rules -->
<!-- /ko -->

However I'm not sure if there is an alternative that could be used - there a workaround or other ideas on this?

Enable two-way binding for "value" and "checked"

In current version, "value" and "checked" bindings are converted to attr binding like the others.

<input type="text" value="{{ firstName }}">

is converted to:

<input type="text" data-bind="attr.value: firstName">

As these attributes are writable, it would be great to convert them in this way:

<input type="text" data-bind="value: firstName">

'Default' filter does not evaluate properly for functions

Expected behavior:
When a function is specified for a binding, execute the function. If the value returned is null or an empty string, replace the value with the Default Value.

Actual Behavior:
When a function is specified for a binding, the function is returned and the Default Value is ignored.

Disable text interpolation for target block

Im does not found this option in docs. Is this exists?

Like:

<div class="{{ works }}">
    <code data-bind="punches: false">
        Some {{ example with }} {{ raw }} text
    </code>
</div>

UPD Fastfix (slow and have bugs):

for (let node of document.body.querySelectorAll('[data-punches="false"]')) {
    node.innerHTML = node.innerHTML
       .replace(/(\{\{|\}\})/g, p => `{{"${p}"}}`)
}

UPD Fastfix No2 (does not work):

for (let node of document.body.querySelectorAll('[data-punches="false"]')) {
    node.innerHTML = node.innerHTML
        .replace(/\{\{/g, '&#123; &#123;')
        .replace(/\}\}/g, '&#125; &#125;');
}

UPD Fastfix No3 (works but has side effects)

for (let node of document.body.querySelectorAll('[data-punches="false"]')) {
    node.innerHTML = node.innerHTML
        .replace(/\{\{([\s\S]*?)\}\}/g, (i, j) => `&#123;&#8203;&#123;${j}&#125;&#8203;&#125;`)
}

Issue with setting 'disabled' property in IE8 with Punches syntax

Given a property on an object:

this.locked = ko.pureComputed(function() { return this.data.access() === 'locked' }, this);

Bound to the view like this:

<button type="button" disabled="{{ locked }}"></button>

IE8 (compat mode) will return true in all cases and lock all inputs. This is not the case when using namespaced attr.disabled or KO attr: { disabled: bindings. Is there any way to remove the attribute altogether when the returned value is falsey? It's in the spec

Enabling Punches breaks foreach/checkbox combination

I have a list of checkboxes that are being populated by a template, and use the "checked" data-binding (on the checkbox element) to determine if the checkbox should be automatically checked after loading data and applying bindings to the DOM.

If I enable punches on the page, my checkboxes fail to auto-check themselves; however if I do not enable punches, it works as intended. Any thoughts what may be causing this?

Here is an example fiddle with punches enabled: http://jsfiddle.net/emes001/u42wubyw/

To reproduce the problem, run the solution as is, then comment out ko.punches.enableAll(); and run it again.

add {model.field} support

It would be handy to have an opportunity to select opening and closing strings for interpolation. Say, not-doubled curly braces can be preferred by someone as me :)

Make Bower friendly

Lots of people use package manager like Bower to manager their js dependencies, which needs a built version of the source in the repo. Would it be possible to make this bower friendly by removing the .gitignore from the build output directory so the built versions can be grabbed via bower.

I guess another alternative is another dedicated repo with the sources.

Thanks,

Adam

building kockout.punches on windows ?

Is it possible to build the library on windows ?
if it is not possible can you plz change the build system and use gulpjs ( or grunt) instead.
that way it will be easier for windows users to contribute.

nested foreach doesn't work

If you swap the nested foreach below with a standard <!-- ko foreach: licenses --> it starts working.

    {{#foreach: products}}
        <div>{{productName}}
        {{#foreach: licenses}}
            <div>{{licenseGuid}}</div>
        {{/foreach}}
       </div>
    {{/foreach}}

Confusing file structure in npm package

I recently spent 1 hour of trying to debug why attribute interpolation wasn't working at all. Finally I found that I incorrectly used the js files from build/output folder (just as they are in knockout npm package) instead of the ones in the root.

The two files in the build/output folder are an old version (0.2.1), that's why it wasn't working. Please do something if you can, so in the future no more victims will get confused by this.

{{#foreach}} not working with JSON array

I'm using {{#foreach: orders}} to display a list of orders fetched from a .json file. The orders are held in a ko.observableArray().

I'm receiving the following error when using Knockout 3.4.0 and KO Punches 0.5.1 with ko.punches.enableAll(); defined:

Uncaught ReferenceError: Unable to process binding "text: function (){return orderId }"
Message: orderId is not defined

However, if I use the KO native data-bind="foreach: orders", this code works as expected.

Here's the code:

HTML

<table class="table table-hover">
    <tbody>
        {{#foreach: orders}}
        <tr>
            <td class="fixed"><i class="glyphicon glyphicon-shopping-cart"></i></td>
            <td><a href="javascript:;">{{orderId}}</a></td>
            <td>{{orderStatusTypeDescription}}</td>
            <td>{{orderDate}}</td>
        </tr>
        {{/foreach}}
    </tbody>
</table>

JS ViewModel (snippet)

var vm = this;
this.orders = ko.observableArray();
ctx.svc.getOrders(1)
        .then(function (orders) {
            vm.orders(orders);
        });

JSON returned by service (orders.json)

[
  {
    "orderId": 10001,
    "customerId": 1,
    "orderStatusTypeId": 7,
    "orderStatusTypeDescription": "Accepted",
    "orderDate": "2012-04-23T18:25:43.511Z"
  },
  {
    "orderId": 9631,
    "customerId": 1,
    "orderStatusTypeId": 4,
    "orderStatusTypeDescription": "Cancelled",
    "orderDate": "2012-04-23T18:25:43.511Z"
  },
  {
    "orderId": 9014,
    "customerId": 1,
    "orderStatusTypeId": 8,
    "orderStatusTypeDescription": "Printed",
    "orderDate": "2012-04-23T18:25:43.511Z"
  },
  {
    "orderId": 9000,
    "customerId": 1,
    "orderStatusTypeId": 9,
    "orderStatusTypeDescription": "Shipped",
    "orderDate": "2012-04-23T18:25:43.511Z"
  }
]

IE7 compatibility

Hi,

Lines 79 and 80 in src/interpolationMarkup.js :
firstChar = expressionText[0],
lastChar = expressionText[expressionText.length - 1],
are not compatible with IE7,
firstChar = expressionText.charAt(0),
lastChar = expressionText.charAt(expressionText.length - 1),
seems to work properly in all browsers.

requirejs and "ko is not defined" in knockout.punches

How to set up requirejs shims for knockout 3.0 and knockout.punches?

// used: http://durandaljs.com/

// index.html
...
<script src="lib/require/require.js" data-main="app/main"></script>
...

// app/main.js
requirejs.config({
  paths: {
    'text': '../lib/require/text',
    'durandal': '../lib/durandal/js',
    'plugins': '../lib/durandal/js/plugins',
    'transitions': '../lib/durandal/js/transitions',
    'knockout': '../lib/knockout/knockout-3.0.0',
    'knockout.punches': '../lib/knockout/knockout.punches',
    'bootstrap': '../lib/bootstrap/js/bootstrap',
    'jquery': '../lib/jquery/jquery-2.0.3',
  },
  shim: {
    'bootstrap': {
      deps: ['jquery'],
      exports: 'jQuery'
    },
    'knockout.punches': {
      deps: ['knockout']
    }
  }
});

// modelviews/search.js
define(['plugins/http', 
        'durandal/app', 
        'knockout', 
        'jquery', 
        'knockout.punches'], function (http, app, ko, $) {

  ko.punches.interpolationMarkup.enable();
  // Uncaught ReferenceError: ko is not defined     knockout.punches.js:6
  // 68: ko.punches = {

  //...

});

Filter that outputs HTML?

I was attempting to create a filter that renders Markdown to HTML using marked:

ko.filters['md'] = function (text) {
    return marked(text);
};

Usage:
{{ someMarkdown | md }}

However, text node will escape the HTML output by this, and I was unable to modify punches to use ko html:

document.createComment("ko html:" + expressionText),

since the html bindingHandler does not support virtual elements.

Any ideas on how I could do this?

ko.components params

Would you be interested in adding a feature to use punches style attributes on ko component params?

From:

<my-element params="foo: 'bar', baz: qux"></my-element>

To:

<my-element foo="bar" baz="{{ qux }}"></my-element>

I've not began implementing, but thought I would check here to see if there was any interest.

Support for npm/browserify

Hey man, thanks for the work on this library.

Is it possible for this module to be published into npm?

Normal attr binding stops working?

When I use ko.punches.enableAll(); my <a data-bind="href: hash></a>" stops working.

Is this a bug or by design? Can't seem to be able to enable the attr binding again without removing .enableAll().

Bower

Great work on this btw. Any chance we can get a bower config file?

Filters with custom bindings

So I know I can do:

<span data-bind="text: name | fit:20 | uppercase"></span>

but what I really want to do is:

<div data-bind="someCustomBinding: data | transform | transform2:param"></div>

where data is an array of a known thing, or other complex object. It looks like currently the punches syntax is only supported for text and css.

Is this possible?

Add to website docs: load with requirejs

I wanted to use Knockout punches with requirejs and wondered why a second version of Knockout was being queued; I don't know whether this is evident to frequent require.js users (and I probably won't make the same mistake again), but it took me a while to realize that the module name needed to be changed when (1) knockout.js is not a direct child file of the path defined as baseUrl in the require.js config, or (2), the knockout.js file is defined, eg as ko in the paths config property.

Eg, for (1), my config says the following:

paths: {
   lib: 'lib'
}

And I referenced Knockout in define/require calls like so:

define(['lib/knockout'], function(ko) { ... })

So might be worth mentioning on the website.

Punches flow control in table structures

I'm not sure if this is something that can be fixed in punches or if it is the browser (chrome in my instance) moving things but I'm trying to use if statements to control what elements of a table are displayed. Unless used within a td it does the following:

Markup:

<div>
    <table>
    {{#if: displayData}}
        <thead>
            ...
        </thead>
    {{/if}}
        <tbody>
        {{#if: displayData}}
            ...
        {{/if}}
        </tbody>
    </table>
</div>

Expected:

<div>
    <table>
    <!-- ko if: displayData -->
        <thead>
            ...
        </thead>
    <!-- /ko -->
        <tbody>
        <!-- ko if: displayData -->
            ...
        <!-- /ko -->
        </tbody>
    </table>
</div>

Generated:

<div>
    <!-- ko if: displayData -->
    <!-- /ko -->
    <!-- ko if: displayData -->
    <!-- /ko -->
    <table>
        <thead>
            ...
        </thead>
        <tbody>
            ...
        </tbody>
    </table>
</div>

IE8 textarea value binding

I have an email template editing form that works great on most browsers, but when loading an email template with handlebar style variables {{ }} in IE8, knockout crashes.

As knockout.punches is traversing the DOM looking for text nodes with embedded text bindings on IE8, it finds a text node (nodeType 3) as a child of the textarea control. This doesn't seem to happen in other browsers like Chrome. The result is that the {{ variable }} inside the textarea is replaced with

I'm sure it has to do with IE8 treating textarea differently. Is there something we can do to filter out this scenario?

Publish to NPM

It'd be great if we could get this published as an NPM package for those of us using Browserify/Webpack workflows!

Wrapped callbacks are not working?

Hello! I just started to use your great library!

Unfortunately, looks like wrapped callbacks feature is not working correctly, or I misunderstood its behaviour. If all clicks etc are wrapped in function(){}, my data-bind="click: window.alert('test')" should not be called immediately after page loads? Because it alerts as soon as applyBindings goes on.

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.